Click here to Skip to main content
15,893,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm using the winsock2 API in my VC++ 2008 app.
When the application is running and the socket is connected all the time reading/writing, I unplug the network cable to force a network problem.
In order to check if the connection is down I just send 0 bytes to the socket, but I still returns 0 instead of SOCKET_ERROR.
Does anyone know how to check if the connection is down?
Posted

This is one of the most misunderstood concept from software developers in respect to network admins, that typically arise around of the confusion between "network" and "link".

A soket is a relation between two remote IP addresses. There can be the entire Internet in between: there is no "cable from A to B". An B can be unreachable from A even if the cable in A is plugged.
Think to
A ----- R ----- R ---- R ---- B
        \----R-----R---/

And since who sits on A cannot have the control of the entire state of all the links in between, there is no event local to A that can alone demonstrate A to B reachability.

Unplugging the cable simply makes the network card offline, but doesn't have any effect on IP (that is connectionless).
Of course, you can -with appropriate OS API- check the status of the card, but even if you find it "up" doesn't mean B is reachable.

If you operate on a TCP socket, you have to trust TCP in detecting errors.
Just try send something that requires an acknowledge (hence, more then 0 bytes), and TCP, not receiving it, will resend the data over and over up to the maximum retransmit timeout (usually 40 seconds). At that point TCP will fail and the socket will report the error.
Don't try to escape the waiting before, or make the timeout shorter: that timer are there for the good reason that -if a temporary unreachability happens- TCP must be able to sustain the socket allowing the underlying network routing to find an alternative path without breaking the session.
 
Share this answer
 
Comments
Ashish Tyagi 40 5-Sep-11 2:26am    
Really a good one +5 from me.
C++


tcp_keepalive KeepAlive;
DWORD dJunk;

// Use socket level keep alive for about 5 minutes
// Unless this is done Microsoft will not close the socket
// in the event of a cable / VPN disconnection for 2 hours.
KeepAlive.onoff = 1;
KeepAlive.keepalivetime = 60000;
KeepAlive.keepaliveinterval = 60000;

WSAIoctl( soc, SIO_KEEPALIVE_VALS, &KeepAlive, sizeof( KeepAlive ), NULL, 0, &dJunk, NULL, NULL );





Above will cause a socket ( in a worker thread ) to time out if its waiting for a message.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900