Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);        
}
like image 632
Ayoub M. Avatar asked Jun 19 '11 17:06

Ayoub M.


People also ask

How is TCP disconnection detected?

In TCP there is only one way to detect an orderly disconnect, and that is by getting zero as a return value from read()/recv()/recvXXX() when reading. There is also only one reliable way to detect a broken connection: by writing to it.

How do I know if a TCP socket is closed?

You could check if the socket is still connected by trying to write to the file descriptor for each socket. Then if the return value of the write is -1 or if errno = EPIPE, you know that socket has been closed.

How do I know if my socket is connected?

If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.


1 Answers

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.)

like image 113
Bruno Avatar answered Oct 17 '22 23:10

Bruno