While iterating through socket file descriptors, how can I check if one of them is from a passive socket (listening for connections)?
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.
The most obvious way to accomplish this is having that process call read on the socket for a connection and check whether read returns 0 (i.e. reads zero bytes from the socket), in which case we know that the connection has been closed.
This can be checked with getsockopt(SO_ACCEPTCONN). For example:
#include <sys/socket.h>
int val;
socklen_t len = sizeof(val);
if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &val, &len) == -1)
printf("fd %d is not a socket\n", fd);
else if (val)
printf("fd %d is a listening socket\n", fd);
else
printf("fd %d is a non-listening socket\n", fd);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With