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!
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. Thegethostbyaddrfunction 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.
For example for this list of IPs:
it prints