Detecting a broken socket

Having established a TCP/IP socket with a server, what is the best way
of determining if the connection has been lost (broken cable, server
crash, etc.)? Data is only being written to the socket by the client
and there is no feedback from the server via confirmation messages or
the like.

Similarly, how about the situation where a server is sending data to a
client. Can the client detect the connection has been broken? (yes I
now the data will stop, but it may do that in the course of normal
peration so it’s not a good indicator)

TIA


\


Gregory A. Fedor
gfedor@grc.nasa.


Sent via Deja.com http://www.deja.com/
Before you buy.

Gregory Fedor <gfedor@grc.nasa.gov> writes:

Having established a TCP/IP socket with a server, what is the best way
of determining if the connection has been lost (broken cable, server
crash, etc.)? Data is only being written to the socket by the client
and there is no feedback from the server via confirmation messages or
the like.

You’ll have to play with this, but I’m sure that writing to the socket
will generate an error once the socket is closed. If you are using
non-blocking writes, then you have to check errno to ensure that the
error is not EWOULDBLOCK, as that is really a status return, not an
error.

Similarly, how about the situation where a server is sending data to a
client. Can the client detect the connection has been broken? (yes I
now the data will stop, but it may do that in the course of normal
peration so it’s not a good indicator)

Typically the client waits for data on a select() call. The select()
only returns when there is an event on one of the file descriptors in
the fdset. If the particular fd has an event, and reading it
generates 0 bytes of data, then the socket has closed. This will not
work if you fd is connected to a terminal device in “cooked” mode.

Note that socket timeouts are generally very long. If you cut the
cable between two computers talking TCP/IP, the timeout will take
betwen 5 and 15 minutes.


Andrew Thomas, President, Cogent Real-Time Systems Inc.
2430 Meadowpine Boulevard, Suite 105, Mississauga, Ontario, Canada L5N 6S2
Email: andrew@cogent.ca WWW: http://www.cogent.ca