一直在玩这个。尚未清理干净。它基本上做了nslookup的功能。从文本文件中获取(或多个)主机名并返回相应的IP地址。
def getIPAddresses(file):
emptyList = []
someString = ".com"
with open(file, "r+") as output:
for line in output:
emptyList.append(line)
my_new_list = [x.strip() + someString for x in emptyList]
return(my_new_list)
def lookup():
try:
while True:
enterSomething = input("Enter something: ")
if os.path.exists(enterSomething):
for n in getIPAddresses(enterSomething):
ip_info = socket.getaddrinfo(n, 80)
b = list(["nslookup of " + str(n) +"\n"] + ip_info +(["\n" + "Result of " +str(n)]))
values = ''.join(str(v) for v in b)
abc = values+ "\n"
print()
print(abc)
break
elif not os.path.exists(enterSomething):
print("No such file or directory " + str(enterSomething))
except(UnicodeError):
print("")
所以,如果我有一个包含以下内容的文本文件:
www.google
www.espn
它将返回
nslookup of www.google.com
(<AddressFamily.AF_INET: 2>, 0, 0, '', ('172.217.1.68', 80))(<AddressFamily.AF_INET6: 23>, 0, 0, '', ('2607:f8b0:4006:808::2004', 80, 0, 0))
Result of www.google.com
nslookup of www.espn.com
(<AddressFamily.AF_INET: 2>, 0, 0, '', ('199.181.133.5', 80))
Result of www.espn.com
我的问题是,有一种方法我只能为www.google.com提取相应的IP地址,例如172.217.1.68
和2607:f8b0:4006:808::2004
等等吗?
答案 0 :(得分:0)
所以你的代码返回一个元组,元组可以像列表一样被索引。
这是我测试的内容
google = socket.getaddrinfo('www.google.com', 80)
google[0][4]
returns ('74.125.141.104', 80)
因此得到了相关的IP地址 做
google[0][4][0]
获取
'74.125.141.104'