C++ – TCP Sockets : detect if peer has shut down before sending? (Linux)

TCP Sockets : detect if peer has shut down before sending? (Linux)… here is a solution to the problem.

TCP Sockets : detect if peer has shut down before sending? (Linux)

Are there any direct commands to detect if a peer closes/closes its socket before sending?

I do this :

int sendResult = send( mySD, bufferPtr, numberToSend, MSG_NOSIGNAL );

send() did happily accept the message and seemed to send it (positive return value), only when I tried to send it next time returned an error. This means: I received the warning 1 message too late.

Yes, I used select() beforehand, but it still returns 1 even though the peer is down.

As a workaround, I can do a 0-byte read directly with recv() before calling send(), which tells me “connection OK” (- 1) or “Peer shutdown” (0) and does most of the work :

int readTest = recv( mySD, NULL, 0, MSG_DONTWAIT | MSG_PEEK );

But from a semantic point of view, reading does “feel” wrong when I really want to send, all I really want is a test. So is there a command like “socket status” that allows me to figure out directly what I need? What kind of thing is recv() used internally?

Solution

Since your program is selection-based, I believe you registered sockets for reading and writing fd sets. If so, you will get the option to read the fd set back, and you will eventually “receive” “0” and therefore close the socket.

Related Problems and Solutions