Python实现DNS域名解析的代码

发布时间:2021-01-01编辑:脚本学堂
本文介绍了python解析dns域名的方法,一例python实现dns域名解析的代码,python dns操作实例,有需要的朋友参考一。

DNS域名系统
DNS是一个分布式的数据库,主要用于吧主机名转换为IP地址

例1,获取域名的IP
 

复制代码 代码示例:
#!/usr/bin/python
import sys, socket  
# 获取域名的IP地址  
result = socket.getaddrinfo(sys.argv[1], None)  
print result[0][4]  
 
result = socket.getaddrinfo(sys.argv[1], None)  
counter = 0 
for item in result:  
    print '%-2d:%s' % (counter, item[4])  
     counter += 1 
import sys, socket# 获取域名的IP地址result = socket.getaddrinfo(sys.argv[1], None)print result[0][4]result = socket.getaddrinfo(sys.argv[1], None)counter = 0for item in result: print '%-2d:%s' % (counter, item[4]) counter += 1

例2,根据IP获取域名
 

复制代码 代码示例:
#!/usr/bin/python
import sys, socket  
 
try:  
    #   根据IP地址得到域名地址  
     result = socket.gethostbyaddr(sys.argv[1])  
    print 'Primary hostname:' 
    print ' ' + result[0]  
    # Display the list of available addressed that is also returned  
    print 'nAddress:' 
    for item in result[2]:  
        print '   ' + item  
except socket.herror, e:  
    print "Couldn't look up name:", e 
import sys, sockettry: # 根据IP地址得到域名地址 result = socket.gethostbyaddr(sys.argv[1]) print 'Primary hostname:' print ' ' + result[0] # Display the list of available addressed that is also returned print 'nAddress:' for item in result[2]: print ' ' + itemexcept socket.herror, e: print "Couldn't look up name:", e

例3,获取网络环境信息(www.jb200.com)。
 

复制代码 代码示例:
#!/usr/bin/python
import sys, socket  
 
def getipaddrs(hostname):  
     result = socket.getaddrinfo(hostname, None, 0, socket.SOCK_STREAM)  
    return [x[4][0] for x in result]  
 
# 获取主机名称  
hostname = socket.gethostname()  
print 'Host name:', hostname  
 
print 'Fully-qualified name:', socket.getfqdn(hostname)  
try:  
    # 打印IP地址  
    print 'IP addressed:', ', '.join(getipaddrs(hostname))  
except socket.gaierror, e:  
    print 'Could not get IP addressed:', e