Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if socket is listening in C

While iterating through socket file descriptors, how can I check if one of them is from a passive socket (listening for connections)?

like image 464
Mihai Neacsu Avatar asked Apr 21 '12 15:04

Mihai Neacsu


People also ask

How do I test if my socket is working?

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.

How do you know if a socket is closed?

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.


1 Answers

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);
like image 163
mark4o Avatar answered Sep 20 '22 08:09

mark4o