[ACCEPTED]-How to detect a TCP socket disconnection (with C Berkeley socket)-network-programming

Accepted answer
Score: 20

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

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

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

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

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

Score: 0

Your problem is that you are completely 6 ignoring the result returned by read(). Your code 5 after read() should look at least like this:

if (n == 0) // peer disconnected
    break;
else if (n == -1) // error
{
    perror("read");
    break;
}
else // received 'n' bytes
{
    printf("%.*s", n, buffer);
}

And 4 accepting a new connection should be done 3 in a separate thread, not dependent on end 2 of stream on this connection.

The bzero() call is 1 pointless, just a workaround for prior errors.

More Related questions