0

I try to resolve hosts using socket module via GUI I made using Tkinter here is part of the code , the main issue is the error I receive while resolving routers name

for line in p.stdout:
            fiw = open("1.txt", '+a')
            line = str(line)
            if "Received = 1" in line:
                hostad = socket.gethostbyaddr(ip3 +str(i))
                if hostad:
                    try:
                        print(hostad)
                    except socket.herror:
                        print(hostad)
                fiw.write("Received reply from " + ip3 +str(i)+"\n")
                print("Received reply from " + ip3 +str(i)+"\n")
                print(socket.gethostbyaddr(ip3 +str(i)))

the error :

socket.herror: [Errno 11004] host not found

script won't run further i used print here just for example also i tried pass tried

except socket.herror as err:
              print(err)
              pass

also tried just using pass in this method

2 Answers2

0

You have try ... except around the wrong thing, instead of

hostad = socket.gethostbyaddr(ip3 +str(i))
if hostad:
    try:
        print(hostad)
    except socket.herror:
        print(hostad)

it should be like

try:
    hostad = socket.gethostbyaddr(ip3 +str(i))
    print(hostad)
except socket.herror:
    pass # code to execute in case of error

The error message itself refers to "Reverse DNS Lookup Failure" as explained in Python Sockets: gethostbyaddr : Reverse DNS Lookup Failure

If the hostname formed in line

hostad = socket.gethostbyaddr(ip3 +str(i))

does not have a reverse DNS record, the exception is thrown.

Community
  • 1
  • 1
J.J. Hakala
  • 6,136
  • 6
  • 27
  • 61
  • Do you know other solution to get device version / name , like nmap does? –  Jul 05 '16 at 14:20
-2

i think that you should take a look at this thread

an exception is like a break point, it breaks your for loop..

try it like this :

for line in p.stdout:
   try:
        fiw = open("1.txt", '+a')
        line = str(line)
        if "Received = 1" in line:
            hostad = socket.gethostbyaddr(ip3 +str(i))
            if hostad:
                try:
                    print(hostad)
                except socket.herror:
                    print(hostad)
            fiw.write("Received reply from " + ip3 +str(i)+"\n")
            print("Received reply from " + ip3 +str(i)+"\n")
            print(socket.gethostbyaddr(ip3 +str(i)))
   except:
            pass
Community
  • 1
  • 1
  • The `inner try ... except` is quite pointless, `print` never throws `socket.herror`. The outer `try ... except` catches every exception which is usually bad practise. – J.J. Hakala Jul 04 '16 at 16:18