简体   繁体   中英

Python - IP to hostname script

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()

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)—eg, open a browser and go to Google.

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.

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()

This works:

import socket


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM