resolve in Python a list of IP addresses in a file

Viewed 38

I'm trying to resolve in Python a list of IP addresses in a file. Apparently the question is not new but I don't understand why my small code is not working.

import socket

with open(r'C:\TMG_logs\web_IP_10', 'r') as r_file:
    with open(r'C:\TMG_logs\web_IP_10_hosts', 'w') as w_file:
        for ip in r_file.readline():
            host = socket.gethostbyaddr(ip)
            w_file.write(host + ' - ' + ip + '\n')

I'm getting:

socket.gaierror: [Errno 11001] getaddrinfo failed

And I don't understand why. Thanks in advance for your time!

1 Answers

The readline() method usually return the list of lines with a "\n" in the end. If this is the case, the gethostbyaddr() will of course fail.

Try instead to use this:

import socket

with open(r'C:\TMG_logs\web_IP_10', 'r') as r_file:
    with open(r'C:\TMG_logs\web_IP_10_hosts', 'w') as w_file:
        for ip in r_file.read().splitlines(): # Here is the difference
            host = socket.gethostbyaddr(ip)
            w_file.write(host + ' - ' + ip + '\n')
Related