Module 2 · Lesson 70 of 131

Datagram boundaries and peer credentials

Send and receive datagrams that keep their message boundaries and read the kernel-verified credentials of the sending process.

  • Beginner to advanced
  • 10 min read
  • 75 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM; gcc 13; the unix(7) man pages

Your place in the module
By the end you can 4 objectives
  • Send and receive unix datagrams so that each message keeps its boundaries.
  • Read a peer's pid, uid and gid with SO_PEERCRED and with SO_PASSCRED plus SCM_CREDENTIALS.
  • Bind and connect sockets in the abstract namespace.
  • Explain why abstract names have no filesystem permissions.
Video coming soonDatagram boundaries and peer credentials
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Framing messages on stream sockets
  • A stream socket is a byte stream with no message boundaries; writes merge and split arbitrarily
  • A length-prefixed header tells the reader how many bytes to read, and a loop reassembles partial reads
  • MSG_PEEK inspects queued bytes without removing them
01

Message boundaries on datagram sockets

4 min read

Stream sockets forced you to build framing by hand. Datagram unix sockets keep message boundaries for you, and this lesson adds credential passing and the abstract namespace.

A On a stream socket the kernel is a byte pipe: it may merge ten small writes into one read, or split one large write across several reads. That is why the previous lesson built a length-prefix framing layer by hand. A datagram socket removes that work. Each send, sendto or write on the sending socket produces one datagram, and each recv, recvfrom or read on the receiving socket returns exactly one datagram.

Boundaries come with two obligations. First, connectionless delivery. A stream socket sends to the peer it connected to, but an unconnected datagram socket must be told where each message goes, so sendto takes a destination address every time, and recvfrom returns the sender's address. A datagram socket that will receive must first be bound to a name with bind, otherwise there is no address for a sender to aim at. You may also connect a datagram socket. That does not open a reliable stream; it only records a default destination so send, write and recv can be used without an address on every call. The socket stays message-oriented.

Second, fixed size. The receiving buffer must be large enough for the whole datagram. If it is not, the kernel copies what fits and discards the rest. That truncation is silent in a plain recv, whose return value is only the number of bytes copied; to detect it, check the msg_flags of recvmsg for MSG_TRUNC, or pass MSG_TRUNC to recv to receive the datagram's full length as the return value. The size is also bounded at the top: a datagram larger than the socket's send buffer (SO_SNDBUF) is refused with EMSGSIZE, so a datagram socket removes the need to find message boundaries, not the need to choose a maximum message size.

Choosing a datagram socket is a design decision, not a performance tweak. Use a stream socket when the data is one continuous flow or when messages can be arbitrarily large; use a datagram socket when each message is self-contained and small, as with short chat lines or command requests. The preserved boundary is exactly what saves the receiving side from reimplementing framing.

Stream vs datagram unix socketsStream socketDatagramsocketMessageboundariesnone, bytesmay mergeone send isone receiveSend destinationset byconnect()address persendto()Read returnavailablebytesexactly onemessageShort bufferrest staysfor latertruncated,rest dropped
Stream sockets merge and split bytes; datagram sockets deliver one send as one receive.

The next program sends two messages through a datagram socketpair and shows that they arrive as two messages, not one merged buffer:

c
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    int sv[2];
    if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sv) == -1) {
        perror("socketpair");
        return 1;
    }
    if (write(sv[0], "one", 3) == -1) {
        perror("write");
        return 1;
    }
    if (write(sv[0], "two", 3) == -1) {
        perror("write");
        return 1;
    }

    char buf[16];
    for (int i = 0; i < 2; i++) {
        ssize_t n = recv(sv[1], buf, sizeof(buf), 0);
        if (n == -1) { perror("recv"); return 1; }
        printf("%.*s (%zd bytes)\n", (int)n, buf, n);
    }
    close(sv[0]);
    close(sv[1]);
    return 0;
}

Compile and run it:

bash
gcc -Wall -Wextra -std=c17 -o boundaries boundaries.c
./boundaries
one (3 bytes)
two (3 bytes)

The two writes arrived as two reads. On a stream socket the same two writes might arrive as one six-byte read, or split some other way, because the reader cannot rely on any boundary. The datagram socket keeps the split, so a protocol made of short self-contained messages, such as one datagram per chat line, never has to scan for line endings.

02

Learning who sent a message

5 min read

A datagram socket is connectionless, so a receiver bound to a name can get messages from any process on the machine. A service that must decide who may talk to it needs the sender's identity. Unix domain sockets provide it as credentials: the process id, user id and group id of the peer. Two mechanisms answer two different questions, and this lesson covers both.

SO_PEERCRED answers "who is the peer of this connection". It is a getsockopt option, not a control message, and it returns a It works for connected stream and seqpacket sockets (the client after connect(), the server's accepted socket) and for both ends of a socketpair. A datagram socket that merely called connect() gets no peer credentials this way: Linux records them only for stream-style connections and socketpairs. It needs no cooperation from the peer. The kernel fills in the values, and the peer can neither refuse nor alter them.

c
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    int sv[2];
    if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sv) == -1) {
        perror("socketpair");
        return 1;
    }
    struct ucred peer;
    socklen_t len = sizeof(peer);
    if (getsockopt(sv[0], SOL_SOCKET, SO_PEERCRED, &peer, &len) == -1) {
        perror("getsockopt");
        return 1;
    }
    printf("peer pid=%ld uid=%ld gid=%ld\n",
           (long)peer.pid, (long)peer.uid, (long)peer.gid);
    close(sv[0]);
    close(sv[1]);
    return 0;
}

Compile and run it:

bash
gcc -Wall -Wextra -std=c17 -o peercred peercred.c
./peercred

The printed pid, uid and gid belong to the process that made the socketpair, because both ends are that same process. In a real server the peer is a different process and the values name it. The values on your machine will differ from anything shown here.

SO_PEERCRED has a limit that matters for datagrams: it is a property of a connection. An unconnected datagram receiver has no single peer, so there is nothing for SO_PEERCRED to report. To learn who sent a particular datagram, the receiver asks the kernel to attach credentials to each message. It sets SO_PASSCRED on its own socket, then reads the credentials from the ancillary data of recvmsg as SCM_CREDENTIALS.

c
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    int sv[2];
    if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sv) == -1) {
        perror("socketpair");
        return 1;
    }
    int one = 1;
    if (setsockopt(sv[1], SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) == -1) {
        perror("setsockopt");
        return 1;
    }
    if (write(sv[0], "hello", 5) == -1) {
        perror("write");
        return 1;
    }

    char buf[64];
    char cbuf[CMSG_SPACE(sizeof(struct ucred))];
    struct iovec iov = { buf, sizeof(buf) };
    struct msghdr msg = {0};
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
    msg.msg_control = cbuf;
    msg.msg_controllen = sizeof(cbuf);

    ssize_t n = recvmsg(sv[1], &msg, 0);
    if (n == -1) { perror("recvmsg"); return 1; }

    for (struct cmsghdr *c = CMSG_FIRSTHDR(&msg); c; c = CMSG_NXTHDR(&msg, c)) {
        if (c->cmsg_level == SOL_SOCKET && c->cmsg_type == SCM_CREDENTIALS) {
            struct ucred cred;
            memcpy(&cred, CMSG_DATA(c), sizeof(cred));
            printf("sender pid=%ld uid=%ld gid=%ld\n",
                   (long)cred.pid, (long)cred.uid, (long)cred.gid);
        }
    }
    printf("%.*s\n", (int)n, buf);
    close(sv[0]);
    close(sv[1]);
    return 0;
}

Compile and run it:

bash
gcc -Wall -Wextra -std=c17 -o pascred pascred.c
./pascred

The receiver sets SO_PASSCRED only on its own socket. After that, every datagram that socket receives carries a SCM_CREDENTIALS control message. The receiver supplies the buffer through msg_control and msg_controllen, then walks the list of control messages with CMSG_FIRSTHDR and CMSG_NXTHDR. The kernel wrote the sender's credentials into that buffer; the sender did not volunteer them and cannot change them.

Step by stepReading per-message credentials
  1. Enable: The receiver sets SO_PASSCRED on its datagram socket.

  2. Send: A peer sends a datagram, with no credential work on its side.

  3. Attach: The kernel appends a SCM_CREDENTIALS control message holding the sender's pid, uid and gid.

  4. Receive: recvmsg returns the datagram bytes and the control message together.

  5. Walk: The receiver walks the cmsghdr list to find SCM_CREDENTIALS.

  6. Decide: The receiver checks the credentials before acting on the message.

Kernel-attached credentialsSenderKernelReceiversetsockopt(SO_PASSCRED)sendto(datagram)datagram +SCM_CREDENTIALS1. Receiver → Kernelsetsockopt(SO_PASSCRED)2. Sender → Kernelsendto(datagram)3. Kernel → Receiverdatagram + SCM_CREDENTIALS
The kernel, not the sender, attaches credentials to each received datagram.
Going deeperExplore the mechanism

Two details make credentials trustworthy, and one makes their timing matter.

The kernel checks the values, so a process cannot impersonate another. When the sender attaches nothing, the kernel fills in the sender's process id and its real uid and gid. A sender may attach its own SCM_CREDENTIALS message, but the kernel accepts it only if the pid is the sender's own and the uid and gid each match one of the sender's real, effective or saved IDs; naming any other process or user needs CAP_SYS_ADMIN (for the pid) or CAP_SETUID and CAP_SETGID. An unprivileged sender therefore cannot claim to be someone else.

Timing differs between the two mechanisms. SO_PEERCRED is a snapshot taken when the connection was made, at connect or socketpair time. SCM_CREDENTIALS is captured per message, at the moment of each send. A process that changes its uid with setuid() between connect and send therefore shows the old uid through SO_PEERCRED and the new uid through SCM_CREDENTIALS. The fields differ too: SO_PEERCRED reports the effective uid and gid, while kernel-filled SCM_CREDENTIALS carries the real ones. If your decision depends on the sender's identity right now, use SCM_CREDENTIALS; if it depends on who established the connection, SO_PEERCRED is enough.

Note that credentials travel in ancillary data, which only recvmsg exposes. recv and recvfrom cannot return control messages, so reading SCM_CREDENTIALS always goes through recvmsg.

03

The abstract namespace

4 min read

Every unix socket address seen so far in this module has been a pathname: a struct sockaddr_un whose sun_path holds a filesystem path such as /tmp/my.sock. That socket shows up as a file. You see it with ls, it carries permissions, and it must be unlinked when you are done, or it lingers as a stale entry that makes the next bind fail.

Linux offers a second kind of unix socket address: the Its sun_path begins with a null byte, and the name is the bytes that follow. Because the first byte is null, the kernel knows it is not a pathname and creates no file in the filesystem. Abstract names are a Linux extension, not POSIX. The abstract name may be up to 107 bytes: one less than sun_path's 108, because the first byte is the null marker.

c
#define _GNU_SOURCE
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

int main(void) {
    int fd = socket(AF_UNIX, SOCK_DGRAM, 0);
    if (fd == -1) { perror("socket"); return 1; }

    struct sockaddr_un a = {0};
    a.sun_family = AF_UNIX;
    a.sun_path[0] = '\0';
    strncpy(a.sun_path + 1, "m2s09b4", sizeof(a.sun_path) - 2);

    socklen_t len = (socklen_t)(offsetof(struct sockaddr_un, sun_path)
                                + 1 + strlen("m2s09b4"));
    if (bind(fd, (struct sockaddr *)&a, len) == -1) {
        perror("bind");
        return 1;
    }
    printf("bound to abstract name (no file on disk)\n");
    close(fd);
    return 0;
}

The address length is the critical detail: offsetof(struct sockaddr_un, sun_path), plus one byte for the leading null, plus the length of the name. Passing a full sizeof(struct sockaddr_un) instead makes the kernel read the name plus trailing zero bytes, which silently changes the name you think you bound.

Why use an abstract name at all? Having no file brings three practical benefits. First, no cleanup: the name disappears automatically when the socket closes, so there is no stale file to unlink and no EADDRINUSE left behind by a crashed predecessor. Second, no location constraints: sun_path is a fixed 108 bytes either way, but an abstract name does not need to sit inside a writable directory or an existing mount point. Third, autobind: if a socket calls bind() with an address length of only sizeof(sa_family_t), or has SO_PASSCRED set while still unbound, Linux gives it a unique abstract name automatically, so a datagram client that needs a return address does not have to invent one.

The security properties point the other way. A pathname socket is protected by the permissions of its directory and its file: only processes allowed on that path can reach it. An abstract socket has no file, so there is no permission to set and no owner to check. Any process on the machine that knows the name can bind it or send to it, and a short constant name is guessable. The name itself is the only gate.

{{< callout type="warning" >}}Abstract names are a convenience, not an isolation boundary. When the namespace must decide who may connect, use a pathname socket inside a directory with restrictive permissions, and authenticate senders with the kernel-supplied credentials from the previous section.{{< /callout >}}

Pathname vs abstract socket namesPathnamesocketAbstractsocketFilesystem entryyes, a socketfileno entryPermissionsdirectory andfile bitsnone, name isthe gateCleanupunlink() whendoneautomatic onclosePortablePOSIXLinux only
A pathname socket is a file with permissions; an abstract socket has no filesystem entry at all.

You now have the rest of the unix socket toolbox: datagrams that keep their boundaries, kernel-verified credentials for each sender, and a namespace that needs no file cleanup. The next lesson, Starting minichat, builds a working chat server on a pathname stream socket, using the length-prefixed framing from the framing lesson, a type byte per message and a nick handshake. That server is the lab you will build there.

Key takeaways

  • A datagram socket delivers each send as exactly one message; an undersized receive buffer truncates the datagram and discards the excess.
  • SO_PEERCRED reports the credentials of a connected peer; SO_PASSCRED makes the kernel attach SCM_CREDENTIALS to each datagram the socket receives.
  • The kernel, not the sender, fills in the credentials in SCM_CREDENTIALS, so a peer cannot impersonate another process.
  • Abstract socket names have no filesystem entry, so there is no file to unlink and no permissions to set; the name itself is the only access gate.
Reflect
  1. Explain to a colleague, in two sentences: send and receive unix datagrams so that each message keeps its boundaries.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close