Python – Read a list of hostnames and resolve to IP addresses

pythonsockets

i'm attempting to read a plain text file and resolve each IP address and (for now) just spit them back out on-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

Currently I'm 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

Googling that error doesn't seem to help me…
The text file only contains one line at the moment (test.com) but i get the same error even with multiple lines/different hosts.

Any suggestions?

Thanks!

Best Answer

import socket
with open("test.txt", "r") as ins:
    for line in ins:
        print socket.gethostbyname(line.strip())