本节内容:
gethostbyaddr、gethostname实例。
例1,gethostbyaddr()的例子
如下:
#!/usr/bin/python
#
#site: www.jb200.com
import sys, socket
def getipaddrs(hostname):
result = socket.getaddrinfo(hostname, None, 0, socket.SOCK_STREAM)
return [x[4][0] for x in result]
# the name of the local machine
hostname = socket.gethostname()
try:
print "IP addresses:", ", ".join(getipaddrs(hostname))
except socket.gaierror, e:
print "Couldn't not get IP addresses:", e
例2,使用gethostname、socket.getfqdn获取本地计算机的完全限定名称。
代码:
#!/usr/bin/python
#
#site WWW.jb200.com
import sys, socket
hostname = socket.gethostname()
# Try to get the fully-qualified name.
print "Fully-qualified name:", socket.getfqdn(hostname)