问题描述
我想从文本文件中解析主机名的IP地址。下面的代码适用于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))
对于ipv6,我使用了以下代码,当文本文件中只有一个主机名时,它可以正常工作。如果文本文件中有多个主机名,则会出现此错误“ gaierror:[Errno 8]节点名或提供的服务名,或者未知”
import socket
with open('hostname1.txt') as f:
hostname = f.readlines()
for website in hostname:
ais = socket.getaddrinfo(website,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
保留换行符,因此您的hostname
列表为['google.com\n','yahoo.com\n','facebook.com\n','cnn.com\n']
您在IPV4部分而不是IPV6部分中剥离了\nl
。
使用以下内容:
ais = socket.getaddrinfo(website.rstrip(),0)
您将获得正确的结果。