What happens to sockets when I unplug a network cable?

What address are you using for "Con A"? If you are using an address that is bound to the external network adapter, even though you're talking to the same machine, then what you describe could happen.

What you can do is use the address localhost (127.0.0.1) for "Con A", which should be completely independent of what happens on the external network.


On some platforms (windows) pulling the network cable tells the network stack to activly invalidate open socket connections associated with the interface.

In this scenario pulling a network cable is actually a bad test because it provides positive feedback to your application that it may not receive in a real life situation.

One common error for people to make when writing client/server applications is to not incporporate an application layer keep-alive or at least enable keepalives at the transport layer. An application recv()ing data can otherwise be forever oblivious to any failure condition until it write()s and the write fails due to transport layer timeout.


Pulling the network cable has different effects depending on the OS you're running. As another poster said, Windows detects it and invalidates any existing connections. Your application should get a connection closed message in that case.

My Linux server on the other hand deals with it quite gracefully. After an extended (30-40 seconds) de-cabling the other day the SSH connection from my laptop to the server was still happily available and responsive.

As long as the cable is not unplugged longer than the TCP timeouts the stack should be able to buffer up packets and retransmit them as soon as possible. TCP is designed for that. If you're not using TCP then the packets will fall out of the Ethernet hole and evaporate into the atmosphere.

@einstein: If you're using select() or derivatives it pays to never select with a NULL timeout. Always have a sensible timeout and check the socket status if it expires.

Tags:

C#

.Net

Sockets