Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

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

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 anything for a long time and thats OK).

It mostly detects error conditions when clients crash or machines are turned off, but it takes many minutes to notice when the network cable to the client has been unplugged and I would prefer it to notice this condition as soon as possible.

I don't have control over the clients and I can't make them send something like a "ping". My server does send out a "ping" packet to the to the clients (but they won't send a response), but even when the cable is unplugged write() returns the correct number of bytes (I see the TCP stack sending retry packets in Wireshark).

What is the best way to notice the loss of connection ? It would be most convenient if I could detect it on the write() call.

I need this to work on Windows and on Linux.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...