how to check tcp peer is closed

2019-08-13 07:44发布

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

2条回答
狗以群分
2楼-- · 2019-08-13 08:16

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).

查看更多
走好不送
3楼-- · 2019-08-13 08:28

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 the MSG_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 get EAGAIN (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 of MSG_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...

查看更多
登录 后发表回答