简体   繁体   中英

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?

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.

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

Best, Peter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM