39

This question will expand on: Best way to open a socket in Python
When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail.

Edit: I tried this:

try:
    s.connect((address, '80'))
except:
    alert('failed' + address, 'down')

but the alert function is called even when that connection should have worked.

1
  • You should always use print_exc() from traceback module in except clause ! that will indicate accidental mistakes.
    – Alex
    Commented Jul 29, 2012 at 9:54

4 Answers 4

48

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.

7
  • 2
    This doesn't seem to be working, even still, the alert function is not being called.
    – UnkwnTech
    Commented Oct 7, 2008 at 7:10
  • 1
    try to move the s.connect out of the try: block. what error will you get?
    – kender
    Commented Oct 7, 2008 at 7:18
  • don't forget to close the socket after testing it is open. :)
    – Paul C
    Commented Feb 5, 2014 at 21:04
  • // , @kender, why did you choose the letter s as the variable name for the socket.socket() object? Is that an informal convention? Commented Jan 11, 2016 at 21:03
  • // , Also, do you think this Python example would work in Python 3.5? Commented Jan 11, 2016 at 21:05
11

You can use the function connect_ex. It doesn't throw an exception. Instead of that, returns a C style integer value (referred to as errno in C):

s =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
s.close()
if result:
    print "problem with socket!"
else:
    print "everything it's ok!"
2
  • 3
    In case of result > 0 you will get the errno value of the failure. You can then do something like print errno.errorcode[result] to get a more useful hint about the failure.
    – Jens
    Commented Nov 5, 2014 at 18:21
  • Whether the connection is up or down: connect_ex() always return "0". It doesnt work for me
    – Coliban
    Commented Feb 6, 2020 at 10:41
6

You should really post:

  1. The complete source code of your example
  2. The actual result of it, not a summary

Here is my code, which works:

import socket, sys

def alert(msg):
    print >>sys.stderr, msg
    sys.exit(1)

(family, socktype, proto, garbage, address) = \
         socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)

try:
    s.connect(address) 
except Exception, e:
    alert("Something's wrong with %s. Exception type is %s" % (address, e))

When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:

Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')
2
  • 1
    // , How does that bit with the (family, socktype, proto, garbage, address) = \ assignment work? BTW, solid answer. Commented Jan 11, 2016 at 21:11
  • A hostname could have multiple IP-addresses - one should loop over all results of the getaddrinfo. But it should be invoked with the protocol ID so as to skip the UDP and like entries: socket.getaddrinfo(address, port, 0, 0, socket.IPPROTO_TCP).
    – Mikhail T.
    Commented Dec 3, 2018 at 17:51
2

12 years later for anyone having similar problems.

try:
    s.connect((address, '80'))
except:
    alert('failed' + address, 'down')

doesn't work because the port '80' is a string. Your port needs to be int.

try:
    s.connect((address, 80))

This should work. Not sure why even the best answer didnt see this.

1
  • 12 years == better to use a Context Manager vs Try and Except? Commented Jan 2, 2022 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.