Skip to content
systemcoding.dev
Networking

Bind to an ephemeral port and read it back with getsockname

Bind to port 0 so Linux picks a free port, then read the chosen number with getsockname() and ntohs() on glibc 2.39. Useful for tests.

1 min read
Summarize in AI

This is how to start a listener without hard-coding a port, which keeps parallel test runs from colliding. Binding to port 0 asks Linux 6.8 to choose a free port from the ephemeral range, and getsockname() tells you which one you got.

ephemeral.cc
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int main(void)
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    addr.sin_port = 0;
    bind(fd, (struct sockaddr *)&addr, sizeof addr);

    socklen_t len = sizeof addr;
    getsockname(fd, (struct sockaddr *)&addr, &len);
    printf("port=%u\n", ntohs(addr.sin_port));
    close(fd);
    return 0;
}
Text
port=41823

The number varies from run to run; the range comes from /proc/sys/net/ipv4/ip_local_port_range, which is 32768 to 60999 by default. len is a value-result argument: you pass the buffer size in and the kernel writes the real size back, so initialise it before the call. See getsockname(2).

The port is only reserved while the socket stays open. If you close it and hand the number to another process, someone else can take it in between.

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.