socket.gaierror:[Erno 11004]读取域列表时出错



我使用下面的代码将文本文件(hosts.txt)读取到列表中,然后尝试使用socket.gethostbyname()将每个文件解析为其IP

import socket
non_blank_count = 0
with open('hosts.txt') as infp:
    for line in infp:
        non_blank_count += 1
print 'IPs to be resolved %d' % non_blank_count     

with open('hosts.txt') as fp:
    content = fp.readlines()
i=0
while i < non_blank_count:
    print("Host: %s : IP: %s") % (content[i], socket.gethostbyname(content[i]))
    i = i+1

每当我尝试这样做时,我都会收到以下错误消息:

Traceback(最后一次调用):文件"test.py",第18行,位于print("Host:%s:IP:%s")%(content[i],socket.ghostbyname(content[i]socket.gaierror:[Erno 11004]getaddrinfo失败

如果我尝试从空闲使用以下功能,它工作正常:

>>> import socket
>>> socket.gethostbyname("google.com")
'74.125.237.99'

我认为这与双引号有关,但我不确定,我尝试了几种变体,它们都有相同的结果(包括用双引号括住主机)

我的hosts.txt文件的格式如下

site.com
www.site.subsite.com
im.another.site.com
etc.com

任何建议都将不胜感激!

file.readlines返回字符串列表,不剥离换行符。您必须使用str.strip 将其剥离

逐行处理文件时,使用文件作为迭代器,而不是使用file.readlines:

import socket
with open('hosts.txt') as fp:
    for line in fp:
        host = line.strip()
        print "Host: {}  IP: {}".format(host, socket.gethostbyname(host))

您需要从每个地址中去掉尾随的'\n'。尝试以下操作:

content[i].rstrip('n'), socket.gethostbyname(content[i].rstrip('n'))

最新更新