How to detect a TCP socket disconnection (with C Berkeley socket)
I am using a loop to read message out from a c Berkeley socket but I am not able to detect when the socket is disconnected so I would accept a new connection. please help
while(true) {
bzero(buffer,256);
n = read(newsockfd,buffer,255);
printf("%s\n",buffer);
}
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.)