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.