Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the socket connection state in C?

I have a TCP connection. Server just reads data from the client. Now, if the connection is lost, the client will get an error while writing the data to the pipe (broken pipe), but the server still listens on that pipe. Is there any way I can find if the connection is UP or NOT?

like image 988
Blacklabel Avatar asked Nov 10 '10 07:11

Blacklabel


People also ask

How do you determine if a 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.

What is TCP socket States?

The states are: LISTEN, SYN-SENT, SYN- RECEIVED, ESTABLISHED, FIN-WAIT-1, FIN-WAIT-2, CLOSE-WAIT, CLOSING, LAST-ACK, TIME-WAIT, and the fictional state CLOSED.

What is a socket connection?

A socket is a communications connection point (endpoint) that you can name and address in a network. Socket programming shows how to use socket APIs to establish communication links between remote and local processes.

How do you connect to socket programming?

The connect() call on a stream socket is used by the client application to establish a connection to a server. The server must have a passive open pending. A server that is using sockets must successfully call bind() and listen() before a connection can be accepted by the server with accept().


1 Answers

You could call getsockopt just like the following:

int error = 0; socklen_t len = sizeof (error); int retval = getsockopt (socket_fd, SOL_SOCKET, SO_ERROR, &error, &len); 

To test if the socket is up:

if (retval != 0) {     /* there was a problem getting the error code */     fprintf(stderr, "error getting socket error code: %s\n", strerror(retval));     return; }  if (error != 0) {     /* socket has a non zero error status */     fprintf(stderr, "socket error: %s\n", strerror(error)); } 
like image 182
Simone Avatar answered Sep 22 '22 18:09

Simone