Search code examples
linuxsocketstcp

Is it possible to check if a non-blocking socket has been shutdown?


I want to check if a socket is still alive before I try to read from it, but it seems like recv() and read() will return 0 regardless. According to the man page:

When a stream socket peer has performed an orderly shutdown, the return value will be 0 (the traditional "end-of-file" return).

But also:

The value 0 may also be returned if the requested number of bytes to receive from a stream socket was 0.

How do I distinguish between these two cases? And if that's not possible, is there some other method to tell is the socket has been shutdown/closed?


Solution

  • Call recv() with a non-zero length and the MSG_PEEK flag. Then check whether the return value is 0. Using MSG_PEEK will prevent this from consuming any of the data -- the next recv() will read it again.