How to detect a TCP socket disconnection (with C Berkeley socket)

The only way you can detect that a socket is connected is by writing to it.

Getting a error on read()/recv() will indicate that the connection is broken, but not getting an error when reading doesn’t mean that the connection is up.

You may be interested in reading this:
http://lkml.indiana.edu/hypermail/linux/kernel/0106.1/1154.html

In addition, using TCP Keep Alive may help distinguish between inactive and broken connections (by sending something at regular intervals even if there’s no data to be sent by the application).

(EDIT: Removed incorrect sentence as pointed out by @Damon, thanks.)

Leave a Comment