Linux 将 IP 转换为主机名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5576744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert IP to hostname
提问by Illusionist
I want to write a python script to convert IP addresses to hostnames. I am using a Linux box. I don't see this information in whois command. Are there any commands that always give the correct hostnames (as accurately as possible)?
我想编写一个 python 脚本来将 IP 地址转换为主机名。我正在使用 Linux 机器。我在 whois 命令中没有看到此信息。是否有任何命令总是提供正确的主机名(尽可能准确)?
回答by ?s??o?
The closest you're likely to get is socket.getfqdn(). It incorporates the results from gethostbyaddr(). Pass it an IP address as a string.
您可能得到的最接近的是socket.getfqdn()。它结合了 gethostbyaddr() 的结果。将 IP 地址作为字符串传递给它。
回答by Tadeusz A. Kad?ubowski
Socketlibrary has an API to do reverse DNS lookups.
import socket
socket.gethostbyaddr("8.8.8.8")
>>> ('google-public-dns-a.google.com', [], ['8.8.8.8'])
Keep in mind that not all IP addresses will have reverse DNS entries, not all aliases might be present in the answer to this query etc.
请记住,并非所有 IP 地址都具有反向 DNS 条目,并非所有别名都可能出现在此查询的答案中等。