Skip to content
systemcoding.dev
Networking

Bind a server to all interfaces with INADDR_ANY

Bind a TCP server to every IPv4 interface with INADDR_ANY and htons on Linux with glibc 2.39, and see why the address is written in network order.

1 min read
Summarize in AI

This is how a server says "accept connections on any local IPv4 address". INADDR_ANY is the wildcard address 0.0.0.0, and on Linux 6.8 with glibc 2.39 it binds the socket to every interface at once, including ones that appear later.

bind_any.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_ANY);
    addr.sin_port = htons(8080);

    if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
        perror("bind");
        return 1;
    }
    puts("bound to 0.0.0.0:8080");
    close(fd);
    return 0;
}
Text
bound to 0.0.0.0:8080

INADDR_ANY is defined as a host-order constant, so wrap it in htonl() like the port goes through htons(). It happens to be zero, which is why code that skips the call still works, but the habit keeps the same lines correct for INADDR_LOOPBACK. The ip(7) manual page describes the address structure.

Binding to the wildcard exposes the service on every network the host is attached to. If the daemon is only for local clients, bind INADDR_LOOPBACK instead.

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.