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!

3
  • 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 3, 2016 at 4:36
  • 2
    Possible duplicate of 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?'. Nov 6, 2017 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 2, 2020 at 21:40

1 Answer 1

35
import socket
with open("test.txt", "r") as ins:
    for line in ins:
        print socket.gethostbyname(line.strip())
5
  • 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 <module> print socket.gethostbyname(line) socket.gaierror: [Errno -2] Name or service not known Jan 3, 2016 at 5:22
  • @proggynewbie weird, which platform did you run your script on?
    – YCFlame
    Jan 3, 2016 at 6:07
  • @proggynewbie try stripping the hostname? I have edited my answer like that
    – YCFlame
    Jan 3, 2016 at 6: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! Jan 3, 2016 at 7:49
  • @proggynewbie maybe the line break character at the end of the line causes this error, which is eliminated by stripping
    – YCFlame
    Jan 3, 2016 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.