Testing socket connection in Python

It seems that you catch not the exception you wanna catch out there 🙂

if the s is a socket.socket() object, then the right way to call .connect would be:

import socket
s = socket.socket()
address="127.0.0.1"
port = 80  # port number is a number, not string
try:
    s.connect((address, port)) 
    # originally, it was 
    # except Exception, e: 
    # but this syntax is not supported anymore. 
except Exception as e: 
    print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
    s.close()

Always try to see what kind of exception is what you’re catching in a try-except loop.

You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except statement for each one of them – this way you’ll be able to react differently for different kind of problems.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)