3

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.

1
  • Thanks for the suggestions :D Commented Jun 16, 2016 at 22:46

1 Answer 1

5

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Great. I solved using the settimeout function. Many thanks.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.