基于Python原生asyncio模块对DNS正向和反向的解析

时间:2021-07-29 07:20:40

一、正向解析:域名解析IP地址

import asyncio
import socket domains = [
('www.baidu.com', 'https'),
('cn.bing.com', 'https'),
('www.2345.com', 'https'),
] async def main(loop, domains):
domain_ip = {}
for domain in domains:
info = await loop.getaddrinfo(
*domain,
proto=socket.IPPROTO_TCP,
)
for host in info:
if domain[0] in domain_ip:
domain_ip[domain[0]].append(host[4][0])
else:
domain_ip[domain[0]] = [host[4][0]]
return domain_ip # 事件环循
event_loop = asyncio.get_event_loop()
try:
get_future = asyncio.ensure_future(main(event_loop, domains)) # 相当于开启一个future
event_loop.run_until_complete(get_future)
print(get_future.result())
finally:
event_loop.close()

输出的结果

{'www.baidu.com': ['14.215.177.39', '14.215.177.38'], 
'cn.bing.com': ['202.89.233.101', '202.89.233.100'],
'www.2345.com': ['121.201.101.42']}

二、反向解析:IP地址解析域名

import asyncio

ip_ports = [
('66.33.211.242', 443),
] async def main(loop, ip_ports):
dns_dict = {}
for ip_port in ip_ports:
info = await loop.getnameinfo(ip_port)
if ip_port in dns_dict:
dns_dict[ip_port[0]].append(info)
else:
dns_dict[ip_port[0]] = info
return dns_dict event_loop = asyncio.get_event_loop()
try:
get_future = asyncio.ensure_future(main(event_loop, ip_ports)) # 相当于开启一个future
event_loop.run_until_complete(get_future)
print(get_future.result())
finally:
event_loop.close()

输出结果

{'66.33.211.242': ('apache2-zoo.george-washington.dreamhost.com', 'https')}