d3llafr33
d3llafr33

Reputation: 347

Set correctly timeout when connection fails on Python socket

I'm starting to learn python socket and the TCP/IP model, so I'm at very beginning. I have this simple piece of code that works correctly as expected:

import socket
from datetime import datetime

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
start = datetime.now()
try:
    s.connect(("www.stackoverflow.com", 80))
    s.close()

except Exception as e:
    print "Error : ", e

print datetime.now() - start

In this case it work correctly, but if I change the port and I use another one, for example 81 (just for testing), the socket doesn't connect (as expected). But I have to wait more or less 20 seconds before execute the print statement (the last line). I would like to understand how can I make it faster, so when the connection fails, or the port is closed, I receive a response error and I don't wait so much time. Also I would like to understand why it has this behaviour, and how I can I set properly a timeout. Probably this is a newbie question, but all your responses and suggestions will be appreciate. Many thanks.

Upvotes: 3

Views: 8862

Answers (1)

rrauenza
rrauenza

Reputation: 6993

Use socket.settimeout()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)                           
s.settimeout(1.0)   

This sets the timeout to 1 second.

socket.settimeout(value)

Set a timeout on blocking socket operations. The value argument can be a nonnegative float expressing seconds, or None. If a float is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. Setting a timeout of None disables timeouts on socket operations. s.settimeout(0.0) is equivalent to s.setblocking(0); s.settimeout(None) is equivalent to s.setblocking(1).

Upvotes: 5

Related Questions