Skip to content
systemcoding.dev
Networking

Check if a socket is listening with SO_ACCEPTCONN

Test whether a descriptor is a listening socket with getsockopt(SO_ACCEPTCONN) on Linux, for example to tell an inherited listener from a client socket.

1 min read
Summarize in AI

This is how a program tells whether a descriptor it inherited is waiting for connections. SO_ACCEPTCONN is a read-only option that is 1 once listen() has been called on the socket.

acceptconn.cc
#include <stdio.h>
#include <sys/socket.h>

int is_listening(int fd)
{
    int v = 0;
    socklen_t len = sizeof v;
    if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &v, &len) < 0)
        return -1;
    return v;
}

int main(void)
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    printf("before: %d\n", is_listening(fd));
    listen(fd, 8);
    printf("after:  %d\n", is_listening(fd));
    return 0;
}
Text
before: 0
after:  1

The check is useful for socket activation. A service started by systemd receives descriptors starting at 3, and verifying SO_ACCEPTCONN plus SO_TYPE confirms each one is what the unit file promised before the program uses it. The call fails with ENOTSOCK if the descriptor is not a socket at all, so -1 is a distinct answer from 0.

You cannot set the option; only listen() changes it. The socket(7) page lists it, and POSIX includes it as well. On Linux 6.8 an unbound socket that has not called listen() answers 0.

Taggedclinux
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.