1
votes

I have create a script to resolve IP to hostname. The script does not resolve the hostname, it gives the following error:

cannot resolve hostname: 10.10.10.10 [Errno 11004] getaddrinfo failed cannot resolve hostname: 10.10.10.10 [Errno 11004] getaddrinfo failed

Please suggest. I'm new to python. The text file contains more than 1000 IPs.

#!/usr/bin/python
import socket
pfile = open ('C:\\Python27\\scripts\\test.txt')
while True:
    IP = pfile.readline()
    if not IP:
        break
    try:
        host = socket.gethostbyaddr("IP")
        print host, IP
    except socket.gaierror, err:
        print "cannot resolve hostname: ", IP, err
pfile.close()
4
Does it work for any of them? Did you try something simpler, without the file? - Ry-♦
"IP" is a string, you probably wanted to pass IP at the least. - FatalError
There are some errors in this code. For example socket.gethostbyaddr("IP") will never work, because you check for the host of the string "IP" instead of the variable IP. - Thomas Skowron
Tried with IP does not work same type of error message. - user2820987

4 Answers

4
votes

There are two problems here.

First, as FatalError pointed out, you're not looking up the value of the IP variable, but the string "IP".

Second, pfile.readline() is going to leave a trailing newline at the end of the IP string, so it's still going to fail.

So:

host = socket.gethostbyaddr(IP.rstrip())

Also, on some platforms, if your DNS isn't working, gethostbyaddr will fail even when given an IP address. So, you may want to do a simple test on the machine you're running the script on (if it's not the same machine you're already using for SO)—e.g., open a browser and go to Google.

0
votes

As far as I can tell, there are different problems.

The line:

host = socket.gethostbyaddr("IP")

will fail because of the string. To fix this, use host = socket.gethostbyaddr(IP).

Furthermore, the error you posted here is caused by 10.10.10.10 being a private IP. The ranges 10.0.0.0–10.255.255.255, 172.16.0.0–172.31.255.255 and 192.168.255.255 are private network blocks; socket.gethostbyaddr() is not able to resolve these addresses. See https://tools.ietf.org/html/rfc1918 for more information about private blocks.

0
votes

After a little Googling, I got it to work in Python 3 as follows:

import socket
pfile = open ('C:\\TEMP\\IPs.txt')
while True:
  IP = pfile.readline()
  try:
    host = socket.gethostbyaddr(IP.rstrip())
    print(IP,host)
  except Exception as e:
    print(IP,"NULL")
pfile.close()
-1
votes

This works:

import socket


IP = "www.google.ca"
host = socket.gethostbyaddr(IP)
print host, IP