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

前端 未结 3 539
轮回少年
轮回少年 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条回答
  •  旧时难觅i
    2020-12-12 01:05

    Sorry, but there is no way to detect an abnormal disconnection in a timely manner without pings/keepalives. Even the OS does not always know the cable has been pulled. That is why write() still works - the socket is happily buffering the data in its outgoing buffer, waiting to send it at a later time, because the socket state has not been invalidated by the OS yet. Eventually, the socket will time out internally, at which time the OS can finally invalidate the connection and let the socket report errors on subsequent operations. But that can take a long time, as you have noticed.

    Since you cannot send application-layer pings, try enabling socket-layer keep-alives, at least. That might help. On Windows 2000+ only, you can use the SIO_KEEPALIVE_VALS socket option via WSAIoctl(), which lets you set the actual timer values of the keep-alives. On all platforms, you can use the SO_KEEPALIVE option via setsockopt(), but that does not let you configure the timer values, so defaults are used instead.

提交回复
热议问题