How do I avoid blocking in the connect() method of a socket?
The select module is commonly used to help with non-blocking I/O on sockets. This module lets you check if one or more sockets are ready for reading or writing, without having to block for an unknown period of time.
To prevent the TCP connect from blocking, you can set the socket to non-blocking mode. Then when you call the connect method, you will either connect immediately (unlikely) or get an exception that contains the error number in its errno attribute. The value errno.EINPROGRESS indicates that the connection is in progress, but hasn’t finished yet. Different OSes will return different values, so you’re going to have to check what’s returned on your system.
You can use the connect_ex method to avoid creating an exception. It will just return the errno value. To poll, you can call connect_ex again later — 0 or errno.EISCONN indicate that you’re connected — or you can pass this socket to select to check if it’s writable.
CATEGORY: library

Comment:
The opening sentence describes "asynchronous" operation. This is really non-blocking operation. The two aren't synonyms: select helps you with non-blocking operations, but has nothing to do with asynchronous ones. Further down, the discussion about errnos returned by connect or connect_ex might benefit from a mention of the correct way to determine the actually errno a non-blocking connection attempt fails with. You should use getsockopt(SOL_SOCKET, SO_ERROR), not a second connect call, in order to be portable across more platforms.
Posted by Jean-Paul (2006-11-06)