Read the list of host names and resolve IP addresses

I am trying to read a simple text file and resolve each IP address and (for now) just spit them back onto the screen.

import socket

f = open("test.txt")
num_line = sum(1 for line in f)
f.close()

with open("test.txt", "r") as ins:
        array = []
        for line in ins:
                array.append(line)

for i in range(0,num_line):
        x = array[i]
        print x 
        data = socket.gethostbyname_ex(x)
        print data

I am currently getting the following:

me@v:/home/# python resolve-list2.py
test.com

Traceback (most recent call last):
  File "resolve-list2.py", line 15, in <module>
    data = socket.gethostbyname_ex(x)
socket.gaierror: [Errno -2] Name or service not known

It seems that this error does not help me ... The text file contains only one line (test.com), but I get the same error even with multiple lines / different hosts.

Any suggestions?

Thanks!

+4
source share
1 answer
import socket
with open("test.txt", "r") as ins:
    for line in ins:
        print socket.gethostbyname(line.strip())
+13
source

Source: https://habr.com/ru/post/1622567/


All Articles