1

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

asked Feb 20, 2014 at 22:56
2

2 Answers 2

3

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.

answered Feb 20, 2014 at 23:01
Sign up to request clarification or add additional context in comments.

3 Comments

i had a feeling. but i've built a simple p2p client. i had my friend run it on his machine before I tried to connect, so python on his machine should have opened the socket for listening. Would this not be sufficient to circumvent the firewall? Or must something be done manually?
@Ethan Sometimes you may need to configure the firewall too. Try executing your code with firewall disabled and see if it works. If it works then it may be the firewall issue else it would be a different issue.
@Ethan You can configure the firewall manually or use UPnP to forward a port programatically (no sure how to do that with Python).
1

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.

answered Mar 1, 2014 at 6:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.