Ingmar
Ingmar

Reputation: 2638

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

Is there any direct command to detect whether the peer has shut down / closed its socket before sending?

I do this:

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

send() does happily accept the message and seems to send it (positive return value), only the next time I try sending it returns an error. That means: I get the warning 1 message too late.

Yes, I am using select() beforehand, yet it still returns 1 even when the peer has shut down.

As a workaround, I can perform a 0-byte-read with recv() directly before calling send(), that tells me "Connection OK" (-1) or "Peer shutdown" (0) and does pretty much the job:

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

But from the semantic standpoint, it does "feel" wrong to read when I actually want sending, what I actually want is a mere test. So is there a command such as "socket status" where I can directly figure out what I need? The kind of thing recv() uses internally?

Upvotes: 3

Views: 2476

Answers (2)

ilmiacs
ilmiacs

Reputation: 2576

I guess there is a reason why protocols on top of sockets do implement ping-pong mechanisms?

Best, Peter

Upvotes: 0

Kolli Ashok Kumar
Kolli Ashok Kumar

Reputation: 66

As your programs is select based, I believe you register the socket both for read and write fd set. If yes, you would be getting a select return for read fd set and you would be 'recv'ing eventually '0' and hence closing the socket.

Upvotes: 4

Related Questions