I'm learning to use sockets in python and something weird is happening.
I call socket.connect in a try block, and typically it either completes and I have a new socket connection, or it raises the exception. Sometimes, however, it just hangs.
I don't understand why sometimes it returns (even without connecting!) and other times it just hangs. What makes it hang?
I am using blocking sockets (non-blocking don't seem to work for connect...), so I've added a timeout, but I'd prefer connect to finish without needing to timeout.
Perhaps, when it doesn't hang, it receives a response that tells it the requested ip/port is not available, and when it does hang there is just no response from the other end?
I'm on OSX10.8 using python2.7
-
sure. can i just post a github link, or is that frowned upon?Ethan– Ethan2014年02月20日 23:08:15 +00:00Commented Feb 20, 2014 at 23:08
-
github.com/ebuchman/p2p_py/blob/master/p2p.pyEthan– Ethan2014年02月20日 23:23:07 +00:00Commented Feb 20, 2014 at 23:23
2 Answers 2
When connect() hangs it is usually because you connect to an address that is behind a firewall and the firewall just drops your packets with no response. It keeps trying to connect for around 2 minutes on Linux and then times out and return an error.
3 Comments
Firewall may be the explanation behind this unexpected response. Rather than supposing the remote firewall accepts connection, using timeout is the best option. Since, making a connection is a swift process and within a network, it won't take longer time. So, give a proper timeout so that you can tell that the host is either down or dropping packets.