Skip to main content
 首页 » 编程设计

python之socket,gethostbyaddr 的返回和写入文件如何拆分

2025年05月04日12lori

我有一个脚本可以从一个文件中读取地址并使用 socket.gethostbyaddr 查找它的主机名,但是这个函数的返回是困惑的并且看起来不正确。

写入目标文件的行是:

destfile.write(str(socket.gethostbyaddr(ip))) 

读到8.8.8.8时结果是这样的:

('google-public-dns-a.google.com', [], ['8.8.8.8]) 

但是,我只需要第一个输出,google-public-dns-a.google.com。我希望将其写入文件并如下所示:

8.8.8.8 resolves to google-public-dns-a.google.com 

有人知道怎么拆分吗?如果需要,可以提供更多代码。

请您参考如下方法:

好吧,第一步是将一行拆分成多行:

host = socket.gethostbyaddr(ip) 

现在,您可以为所欲为。如果您不知道要做什么,请尝试打印出 host 和 type(host)。您会发现它是一个包含 3 个元素的 tuple(尽管在本例中,您可以从写入文件的字符串中猜到),而您想要第一个。所以:

hostname = host[0] 

或者:

hostname, _, addrlist = host 

现在,您可以将其写入输出:

destfile.write('{} resolves to {}'.format(ip, hostname)) 

另一种发现相同信息的方法是查看 the documentation ,它说:

Return a triple (hostname, aliaslist, ipaddrlist) where hostname is the primary host name responding to the given ip_address, aliaslist is a (possibly empty) list of alternative host names for the same address, and ipaddrlist is a list of IPv4/v6 addresses for the same interface on the same host (most likely containing only a single address).

或者使用解释器中的内置帮助:

>>> help(socket.gethostbyaddr) 
gethostbyaddr(host) -> (name, aliaslist, addresslist) 
 
Return the true host name, a list of aliases, and a list of IP addresses, 
for a host.  The host argument is a string giving a host name or IP number.