[英]gaierror: [Errno 8] nodename nor servname provided, or not known
I want to resolve the ip address of hostnames from a text file.我想从文本文件中解析主机名的 ip 地址。 Below code works fine for ipv4 address:
下面的代码适用于 ipv4 地址:
hostname1.txt:
google.com
yahoo.com
facebook.com
cnn.com
with open('hostname1.txt','r') as hostnames:
for website in hostnames:
ip = socket.gethostbyname(website.strip())
print ('{0} ip address is: {1}'.format(website,ip))
For ipv6, I used the below code and it works fine when there is only one hostname in the text file.对于 ipv6,我使用了下面的代码,当文本文件中只有一个主机名时它工作正常。 if there are multiple hostnames in the text file, I get this error "gaierror: [Errno 8] nodename nor servname provided, or not known"
如果文本文件中有多个主机名,我会收到此错误“gaierror: [Errno 8] nodename nor servname provided, or not known”
import socket
with open('hostname1.txt') as f:
hostname = f.readlines()
for website in hostname:
ais = socket.getaddrinfo(website,0,0,0,0)
for result in ais:
ip = result[-1][0]
print ('{0} ip address is {1}'.format(website,ip))
gaierror: [Errno 8] nodename nor servname provided, or not known
readlines
keeps newline char, so your hostname
list is ['google.com\n', 'yahoo.com\n', 'facebook.com\n', 'cnn.com\n']
You stripped \nl
in IPV4 part not in IPV6 part. readlines
保留换行符,所以你的hostname
列表是['google.com\n', 'yahoo.com\n', 'facebook.com\n', 'cnn.com\n']
你在 IPV4 部分剥离了\nl
不在 IPV6 部分。 Use the following:使用以下内容:
ais = socket.getaddrinfo(website.rstrip(),0,0,0,0)
and you will get correct result.你会得到正确的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.