How to find the socket connection state in C? How to find the socket connection state in C? c c

How to find the socket connection state in C?


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));}


The only way to reliably detect if a socket is still connected is to periodically try to send data. Its usually more convenient to define an application level 'ping' packet that the clients ignore, but if the protocol is already specced out without such a capability you should be able to configure tcp sockets to do this by setting the SO_KEEPALIVE socket option. I've linked to the winsock documentation, but the same functionality should be available on all BSD-like socket stacks.


TCP keepalive socket option (SO_KEEPALIVE) would help in this scenario and close server socket in case of connection loss.