I have a TCP network connection with remote host.(windows or linux) if remote host process is terminated, recv() fails an I know the connection is closed.
but, is there any way to check if the remote host has closed connection without actually receiving data?
the point is, I want to periodically check if the remote host is still alive but I don't want to give or receive any data.
thank you in advance
If you are monitoring the socket's ready-for-read state via select(), select() will return and indicate that the socket has data ready to read. Then when you try to recv() that data, recv() will either fail (if there was an error) or return 0 (to indicate EOF if the connection was closed cleanly).
To be clear,
recv()
should not fail if the connection has been closed properly. It should return EOF (0 bytes).recv()
will fail is the connection was closed abnormally.To check if the connection has been closed without actually receiving data if it hasn't been, the best you can probably do is call
recvmsg()
with theMSG_PEEK
flag. Ask for just one byte. If the connection has been closed then you'll get EOF (normal close) or an error (abnormal close). If it hasn't been closed, you'll either getEAGAIN
(assuming you put the socket in non-blocking mode) or one byte of data. So, yes, technically you received a byte of data, but because ofMSG_PEEK
the kernel doesn't record the fact that you did, so it's as if you didn't. This all assumes that you've already read out of the kernel's buffer all of the data from the stream that arrived before the prospective error might have happened.Of course rakib's comment applies: "There's no way to check if the remote host is alive, if you don't want to give or recv data.". Meaning this method won't detect scenarios like the remote host disappearing off the network without closing the connection, etc...