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.
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.
#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;
}port=41823The 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.