15

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!

proggynewbie
  • 161
  • 1
  • 1
  • 4
  • 1
    The exception is easy to explain: at least one of the hostnames does not exist or the might be a line not containing a hostname, maybe an empty line at the end. You have to handle both cases. – Klaus D. Jan 03 '16 at 04:36
  • 2
    Possible duplicate of [python: check if a hostname is resolved](https://stackoverflow.com/questions/11618118/python-check-if-a-hostname-is-resolved). once you figure out how to resolve hostname to ip the question becomes 'how do you iterate over a list of strings?'. – Trevor Boyd Smith Nov 06 '17 at 15:58
  • the error without line.strip() is because socket.gethostbyname() takes at least one argument and since it is reading from a list, we need a place holder? – the sherrr Jun 02 '20 at 21:40

1 Answers1

35
import socket
with open("test.txt", "r") as ins:
    for line in ins:
        print socket.gethostbyname(line.strip())
YCFlame
  • 1,251
  • 1
  • 15
  • 24
  • Cool That's a lot simpler/cleaner than what i'm faffing around with, but it still didn't work for me. I got the same error message again: Traceback (most recent call last): File "resolve-list3.py", line 5, in print socket.gethostbyname(line) socket.gaierror: [Errno -2] Name or service not known – proggynewbie Jan 03 '16 at 05:22
  • @proggynewbie weird, which platform did you run your script on? – YCFlame Jan 03 '16 at 06:07
  • @proggynewbie try stripping the hostname? I have edited my answer like that – YCFlame Jan 03 '16 at 06:13
  • Perfect! The line.strip() fixed it! Does that strip out additional characters or something? There shouldn't have been any?? On ubuntu (fresh install) just FYI. I'll mark it as answered when i have the reputation :) Thanks again! – proggynewbie Jan 03 '16 at 07:49
  • @proggynewbie maybe the line break character at the end of the line causes this error, which is eliminated by stripping – YCFlame Jan 03 '16 at 08:13