Use IP list in CSV in python
Question: So, I ahve this list of IP's in a CSV file. Only one column, if I cat the file
they all appear on different lines and the file command tells me it is ASCII
text.

However, when I try to loop though the file and resolve the addesses for the
different IP:s I get the error "socket.herror: [Errno 1] Unknown host".

For some reason the value of the cell isnt properly a string, and I have
trouble converting it to one.

    
    
    from string import rstrip
    from socket import gethostbyaddr
    
    csv_file = open('csv_list.csv', "r")
    
    for line in csv_file:
        dns_name = gethostbyaddr(str(line.rstrip('\n')))
        print "IP: " + line.rstrip('\n') + "DNS Name:" + dns_name[0]
    

Is there any way around this? I have been thinking about converting the file
to a plain textfile, adding all the values from the file to a list so far but
I am not sure what the best solution would be.

Anyone have any ideas?

Thanks in advance!


Answer: Your problem is not the reading of the file (this can be optimized using `with
...`, too) but that one IP cannot be looked up reversely. The `gethostbyaddr`
function throws an exception in that case.

I've made up your sample a bit and now it reports errors not as a crash with
an exception but prints out a message.

    
    
    from string import rstrip
    from socket import gethostbyaddr
    
    with open('csv_list.csv', 'r') as csv_file:
        for line in csv_file:
            ip = line.strip()
            try:
                dns_name = gethostbyaddr(ip)
                print "IP: %s, DNS Name: %s" % (ip, dns_name[0])
            except Exception, e:
                print "IP: %s, DNS lookup error: %s" % (ip, e)
    

For example for this list of IPs:

    
    
    1.2.3.4
    8.8.8.8
    4.4.4.4
    bad IP
    1.2.3
    

it prints

    
    
    IP: 1.2.3.4, DNS lookup error: [Errno 1] Unknown host
    IP: 8.8.8.8, DNS Name: google-public-dns-a.google.com
    IP: 4.4.4.4, DNS lookup error: [Errno 1] Unknown host
    IP: bad IP, DNS lookup error: [Errno 8] nodename nor servname provided, or not known
    IP: 1.2.3, DNS lookup error: [Errno 1] Unknown host
    

