[英]Python - IP to hostname script
I have create a script to resolve IP to hostname. 我创建了一个脚本来将IP解析为主机名。 The script does not resolve the hostname, it gives the following error:
该脚本无法解析主机名,它会出现以下错误:
cannot resolve hostname: 10.10.10.10 [Errno 11004] getaddrinfo failed cannot resolve hostname: 10.10.10.10 [Errno 11004] getaddrinfo failed 无法解析主机名:10.10.10.10 [Errno 11004] getaddrinfo失败无法解析主机名:10.10.10.10 [Errno 11004] getaddrinfo失败
Please suggest. 请提出建议。 I'm new to python.
我是python的新手。 The text file contains more than 1000 IPs.
文本文件包含1000多个IP。
#!/usr/bin/python
import socket
pfile = open ('C:\\Python27\\scripts\\test.txt')
while True:
IP = pfile.readline()
if not IP:
break
try:
host = socket.gethostbyaddr("IP")
print host, IP
except socket.gaierror, err:
print "cannot resolve hostname: ", IP, err
pfile.close()
There are two problems here. 这里有两个问题。
First, as FatalError pointed out, you're not looking up the value of the IP
variable, but the string "IP"
. 首先,正如FatalError指出的那样,您不是在查找
IP
变量的值,而是字符串"IP"
。
Second, pfile.readline()
is going to leave a trailing newline at the end of the IP
string, so it's still going to fail. 其次,
pfile.readline()
将在IP
字符串的末尾留下换行符,因此仍然会失败。
So: 所以:
host = socket.gethostbyaddr(IP.rstrip())
Also, on some platforms, if your DNS isn't working, gethostbyaddr
will fail even when given an IP address. 另外,在某些平台上,如果您的DNS无法正常运行,即使指定了IP地址,
gethostbyaddr
也会失败。 So, you may want to do a simple test on the machine you're running the script on (if it's not the same machine you're already using for SO)—eg, open a browser and go to Google. 因此,您可能希望在运行脚本的计算机上进行简单测试(如果它与用于SO的计算机不同),例如,打开浏览器并转到Google。
As far as I can tell, there are different problems. 据我所知,存在不同的问题。
The line: 该行:
host = socket.gethostbyaddr("IP")
will fail because of the string. 将因为字符串而失败。 To fix this, use
host = socket.gethostbyaddr(IP)
. 要解决此问题,请使用
host = socket.gethostbyaddr(IP)
。
Furthermore, the error you posted here is caused by 10.10.10.10 being a private IP. 此外,您在此处发布的错误是由10.10.10.10作为私有IP引起的。 The ranges 10.0.0.0–10.255.255.255, 172.16.0.0–172.31.255.255 and 192.168.255.255 are private network blocks;
范围10.0.0.0–10.255.255.255、172.16.0.0–172.31.255.255和192.168.255.255是专用网络块;
socket.gethostbyaddr()
is not able to resolve these addresses. socket.gethostbyaddr()
无法解析这些地址。 See https://tools.ietf.org/html/rfc1918 for more information about private blocks. 有关私有块的更多信息,请参见https://tools.ietf.org/html/rfc1918 。
After a little Googling, I got it to work in Python 3 as follows: 稍作搜索后,我将其按如下方式在Python 3中运行:
import socket
pfile = open ('C:\\TEMP\\IPs.txt')
while True:
IP = pfile.readline()
try:
host = socket.gethostbyaddr(IP.rstrip())
print(IP,host)
except Exception as e:
print(IP,"NULL")
pfile.close()
This works: 这有效:
import socket
IP = "www.google.ca"
host = socket.gethostbyaddr(IP)
print host, IP
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.