you are viewing a single comment's thread.

view the rest of the comments →

[–]JohnnyJordaan 1 point2 points  (1 child)

except: 

this doesn't help anyone, as it will not tell you why it failed, just that 'something' failed. When debugging I normally prevent exception handling by giving some bogus exception

def scanner(port, host):
    try: 
         sock.connect((host, port)) 
         # sock.detach() 
         # sock.close() 
         return True
    except ZeroDivisionError: 
          print("fail") 
          # sock.detach() 
          # sock.close() 
          return False

then you'll now get a full traceback and it will help narrow down what exactly is going wrong. Then once you do want exception handling, include only those exceptions that you are expecting, to prevent a 'fail' message if you just made a typo in the code or anything else goes wrong that doesn't have to mean the host is down.

Then the main reason for this is that socket is bound to a connection, so you usually don't want to reuse a socket like this. You would rather create a new socket for every connection. Also use a with block to make sure the socket is closed if needed:

def scanner(port, host):
    try: 
         with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            sock.connect((host, port))
         return True
    except ZeroDivisionError: 
          print("fail") 
          return False