recv() socket function returning data with length as 0

When recv returns a value of 0 that means the connection has been closed.

See the recv man page:

These calls return the number of bytes received, or -1 if an error occurred. The return value will be 0 when the peer has performed an orderly shutdown.

In answer to question #1, yes the socket is now invalid. You must create a new socket and connection for further communications.

Edit

Now as valdo pointed out below, there is also the possibility of having a half-closed TCP connection in which you can't receive any more but you can keep writing to the socket until you've finished sending your data. See this article for more details: TCP Half-Close. It doesn't sound like you have this situation though.

In answer to question #2, there are basically two ways to detect a closed socket. This assumes that the socket went through an orderly shutdown, meaning the peer called either shutdown or close.

The first method is to read from the socket in which case you get a return value of 0. The other method is to write to the socket, which will cause the SIG_PIPE signal to be thrown indicating a broken pipe.

In order to avoid the signal, you can set the MSG_NOSIGNAL socket option in which case send would return -1 and set errno to EPIPE.


To correct numerous misstatements in the existing answers:

  1. Does this mean that the socket i was using until now becomes invalid.

No. It means the peer has closed the connection, or shut it down for output from his end. Your socket is still valid. You can call recv() again, but all you will get is another zero. You can call send() on it too, and if the peer has only shutdown the connection for output the data will be sent.

  1. Do I get any special message like null character or something when this disconnect happens.

No, you get zero return value from recv(). That's what it's for. It is delivered out-of-band, not in the data buffer.

  1. If the socket connection i was having became invalid then why doesnt the recv() socket function throw

Because it's a C API, and there are no throws in C, or in Unix system calls either.

and SOCKET_ERROR.

Because it isn't an error.

Instead why do i receive data of 0 length.

You don't 'receive data of 0 length'. You receive a return value of zero instead of data.


Agree with Robert S. Barnes. Except the claim that the socket is now "invalid".

It's still valid. You can use it. You can even send data to the peer. The only thing you can't do with it is call recv.


If recv returns 0 this means that the peer has closed the socket.

recv won't throw because its a C function.

If there's an error recv will return -1. In which case your application has to check the type of error. Note that a return of -1 does not imply that the peer has closed its socket.

Tags:

C

Sockets

Tcp