4
votes

For a non-blocking net socket, can connect() return 0?

The man page just says it will return -1 and set errno to EINPROGRESS if "The socket is non-blocking and the connection cannot be completed immediately".

What does "immediately" exactly mean?

If connect() CAN return 0 in this case, then under what situation it will return 0 which stands for success? When network between client and server is very good? Or?

3

3 Answers

2
votes

Yes, a non-blocking connect() can return 0 (which means success), although this is not likely to happen with TCP. "Immediately" means that the kernel does not have to wait to determine the status. Situations where you could see this include

  1. UDP sockets, where connect() is basically advisory, allowing send() to be used later, rather than sendto().

  2. Streaming UNIX domain sockets, where the peer is in the same kernel and thus could be scrutinized immediately.

  3. A TCP connection to 127.0.0.1 (localhost).

1
votes

"Immediately", in this context, means without waiting for data to be received from another machine over the network. If it can complete immediately, then zero can be returned. For example, if it's connecting to another process on the same machine, the kernel can complete the connection process immediately.

1
votes

connect(2) is a system call, i.e. an entry into the kernel. This is an opportunity for a multi-tasking OS to preempt your process to do other things.

Now, assuming you are asking about TCP, even for non-blocking sockets, it does not have to, but connect(2) could be implemented so that on the entry it initiates the protocol handshake, and before return to user space checks if it's complete. Then, since OS network stack operates mostly asynchronously with regard to user applications, if your process is preempted in the middle of the system call and switched back to at a later point, the handshake might be already done, and success, zero, returned to the app.