Howto detect that a network cable has been unplugged in a TCP connection?

前端 未结 3 537
轮回少年
轮回少年 2020-12-12 00:25

I have a C++ networking application that accepts TCP connections from clients and then waits on the socket until the client decides to send data (sometimes they won\'t send

3条回答
  •  青春惊慌失措
    2020-12-12 00:54

    Unfortunately, there is no way to distinguish the cable being pulled out at the other end from any other reason for packet loss. Having said that, you can approximate loss of connectivity at the other end as "indefinite packet loss" occurring over a sufficiently long period of time (say T). TCP tracks packet loss, so the general approach for doing this would be:

    • Get the number of unacked bytes in the connection (say it's B)
    • send data, size = N
    • Set a timeout = T, when it fires, check the number of unacked bytes again. If it's B+N, then assume that the other side has lost connectivity. At this point, you could try ICMP echo to verify your assumption.

    Getting TCP-specific information for a connection is not a standard interface on UNIX, and definitely not something portable to Windows. On Linux, there's a socket option called TCP_INFO, which you can call via getsockopt(). Google should give you some examples. I don't know if there's an equivalent option on Windows.

    Another way to do this (i.e. approximate tracking of connectivity loss) is via RAW sockets. Open a RAW socket and filter it to receive only TCP traffic for your connection. Then rather than fetching information from TCP to determine if you are getting anything from the other end, simply wait to receive any packet from the other side. If you get something in the stipulated period, then it means the peer is still up.

提交回复
热议问题