Skip to content
systemcoding.dev
Systems Programming

Fill a sockaddr_un and compute the right address length

Fill sockaddr_un with a bounded copy and pass offsetof(sun_path) plus strlen plus 1 as the length to bind, on Linux with glibc 2.40.

2 min read
Summarize in AI

A struct sockaddr_un has a family and a 108-byte path array on Linux. The length you hand to bind matters more than it looks: the kernel reads addrlen bytes, and for abstract sockets the length is part of the name. For a path socket the exact value is the offset of sun_path, plus the string length, plus the terminating zero.

sockaddr.cc
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

int main(void)
{
    const char *path = "/tmp/demo.sock";
    struct sockaddr_un sa;

    if (strlen(path) >= sizeof sa.sun_path) {
        fputs("path too long\n", stderr);
        return 1;
    }
    memset(&sa, 0, sizeof sa);
    sa.sun_family = AF_UNIX;
    strcpy(sa.sun_path, path);

    socklen_t len = offsetof(struct sockaddr_un, sun_path) + strlen(path) + 1;
    int fd = socket(AF_UNIX, SOCK_STREAM, 0);

    if (bind(fd, (struct sockaddr *)&sa, len) == -1) {
        perror("bind");
        return 1;
    }
    printf("addrlen = %u, SUN_LEN = %zu\n", len, (size_t)SUN_LEN(&sa));
    unlink(path);
    return 0;
}
Text
addrlen = 17, SUN_LEN = 16

The macro SUN_LEN leaves out the terminating zero and is what BSD code often passes; Linux accepts both because it finds the zero itself. Passing sizeof sa also works for path sockets, but it is wrong for abstract names and wastes nothing otherwise, so computing the exact length is the habit that survives a port. Check the length before the copy: strcpy into a 108-byte array is a buffer overflow waiting for a long $HOME. See unix(7).

Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.