DNS 查询

 1 DNS 查询 - Domain Name Server
 2     socket.getaddrinfo("www.baidu.com",None)
 3         返回时一个 tuple list - (family, sockettype, protocol, canonname, socketaddr)
 4         list 的没一个 tuple 元素是一个对应该 域名 host 的一个 web 服务器.
 5         # [(<AddressFamily.AF_INET: 2>, 0, 0, '', ('61.135.169.125', 0)), 
 6         #  (<AddressFamily.AF_INET: 2>, 0, 0, '', ('61.135.169.121', 0))]
 7 
 8 反向查询 - IP 到 hostname    
 9     socket.gethostbyaddr(addr)
10     因为 DNS 信息的授权方式,返回查询得到数据可能是伪造的. 对于反向查询授权是基于IP地址的,
11     所以 DNS 的组织结构中没有办法阻止这种欺骗, 但是可以在程序中做一个反向查找数据的真实性验证:
12         首先方向查找根据 IP 得到一个 hostname , 然后使用反向查询得到的 hostname 做正向查询,
13         如果得到的 IP 跟之前方向查找所用的 IP 一致即反向查到到的 hostname 是真实的,否者就是伪造的.
14         由于正向 DNS 查询是的授权信息是基于域名服务器的, 所以正常查询的信息无法被伪造.
15 
16 例子,
17     import sys, socket
18 
19     def getips(hostname):
20         res = socket.getaddrinfo(hostname, None, 0, socket.SOCK_STREAM)
21         ips = [i[4][0] for i in res]
22         return ips
23 
24     def gethostname(ip):
25         return socket.gethostbyaddr(ip)[0]
26 
27     try:
28         IP = ""
29         hostname = gethostname(IP)
30         ips = getips(hostname)
31     except socket.herror as e:
32         print("Hostname not available for : %s" % IP)
33         print(e)
34     except socket.gaierror as e:      # 询址错误
35         print("Hostname got : %s , however could not forward lookup the host with error : %S" % (hostname, str(e)))
36 
37     if IP not in ips:
38         print("Forward check failed about hostname : %s with IP: %s" % (hostname,IP))
39     else:
40         print("Validated hostname : %s " % hostname)
41 
42 环境信息相关,
43     socket.gethostname()
44         本地的 hostname
45     socket.getfqdn(hostname)
46         通过 hostname 获得 full hostname
47 
48     为了得到完整的域名和 IP 地址, 可以首先通过 gethostname() 方法获得 hostname,
49     接着 通过 getfqdn() 得到完成的信息 - full hostname. 最后使用 getaddrinfo()
50     来获得该域名对应的 IP 地址.
51 
52     例子,
53         import sys, socket
54         def getips(hostname):
55             res = socket.getaddrinfo(hostname, None, 0, socket.SOCK_STREAM)
56             ips = [i[4][0] for i in res]
57             return ips
58 
59         hostname = socket.gethostname()
60         print("hostname is : %s" % hostname)
61         fullhostname = socket.getfqdn(hostname)
62         print("full hostname is %s" % fullhostname)
63         try:
64             print("IP addrs :", ", ".join(getips(fullhostname)))
65         except socket.gaierror as e:
66             print("Could not get IP addr : ",e)
原文地址:https://www.cnblogs.com/zzyzz/p/7986634.html