如何检查tcp peer是否关闭 [英] how to check tcp peer is closed

查看:30
本文介绍了如何检查tcp peer是否关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与远程主机有 TCP 网络连接.(windows 或 linux)如果远程主机进程终止,则 recv() 失败我知道连接已关闭.

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.

先谢谢你

推荐答案

需要明确的是,如果连接已正确关闭,recv() 不应失败.它应该返回 EOF(0 字节).recv() 连接异常关闭会失败.

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.

要检查连接是否已关闭而实际上未收到数据,您可能能做的最好的事情是使用 MSG_PEEK 调用 recvmsg()旗帜.只要求一个字节.如果连接已关闭,那么您将收到 EOF(正常关闭)或错误(异常关闭).如果它尚未关闭,您将获得 EAGAIN(假设您将套接字置于非阻塞模式)或一字节数据.所以,是的,从技术上讲,您收到了一个字节的数据,但是由于 MSG_PEEK,内核不会记录您收到的事实,因此就好像您没有收到一样.这一切都假设您已经从内核缓冲区中读出了在可能发生预期错误之前到达的流中的所有数据.

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.

当然 rakib 的评论适用:没有办法检查远程主机是否活着,如果你不想提供或接收数据.".这意味着此方法不会检测到远程主机在没有关闭连接的情况下从网络上消失等情况...

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

这篇关于如何检查tcp peer是否关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆