Skip to content
Visual explainer 3h to learn 5 steps

Unix domain sockets

Build a local client/server over a Unix socket and pick the right IPC mechanism.

By Invicly Tech, , in Linux System Programming. About 12 minutes to read.

Topic 24 of 42

In short

Unix domain sockets use the full sockets API but stay on one machine, addressed by a file-system path or an abstract name. They are bidirectional, support many clients per server and can even pass open file descriptors between processes. Docker, systemd and databases all use them for local communication.

Explained simply

A Unix domain socket is a network socket that never leaves the computer. It uses the same functions as TCP networking (socket, bind, listen, accept, connect), but instead of an IP address and port, it uses a file path such as /run/app.sock.

It is two-way, so client and server can both send and receive. One server can serve many clients at once, just like a web server. That makes it a natural fit for local services: Docker, systemd, PostgreSQL and many others listen on Unix sockets.

Because the path is a file, normal file permissions decide who may connect. A socket owned by root with mode 660 and group docker lets only members of that group talk to the Docker daemon. The server can also ask the kernel exactly which user is on the other end.

Unix sockets have one trick that no network socket has: a process can send an open file descriptor to another process. The receiver gets its own working handle to the same open file or connection, even if it could never have opened it itself.

Press Play on a diagram to walk through it one step at a time.

ComparePipes vs Unix sockets vs shared memory
Pipes and FIFOs
  • One-way byte stream
  • Simple; ideal for parent and child
  • Kernel copies the data
  • No message boundaries
Unix sockets
  • Two-way, stream or datagram
  • Many clients per server
  • Can pass descriptors and credentials
  • Kernel copies the data
Shared memory
  • No copying, the fastest
  • You add all the synchronisation
  • Best for large or frequent data
  • Bugs are subtle
CompareUnix socket types
SOCK_STREAM
  • Connection, like TCP
  • Byte stream, frame it yourself
  • Most common choice
  • Used by Docker and PostgreSQL
SOCK_DGRAM
  • No connection, like UDP
  • Message boundaries kept
  • Reliable and ordered locally
  • Used by journald's /dev/log
SOCK_SEQPACKET
  • Connection-based
  • Message boundaries kept
  • Reads one message at a time
  • Good for request and reply

In depth

Three kinds of address

A pathname socket is bound to a path in the file system. sun_path holds at most 108 bytes, including the final NUL, so keep paths short. bind creates the socket file, and it stays after the server exits, which is why servers unlink it first. ss -xl lists listening Unix sockets.

An abstract socket is Linux-only: its sun_path starts with a NUL byte, followed by a name. It has no file, so there is nothing to clean up, and it disappears when the last socket closes. It also has no file permissions, so any process in the same network namespace can connect; check the peer's identity yourself.

An unnamed socket comes from socketpair(AF_UNIX, SOCK_STREAM, 0, sv), which returns two already-connected ends. It is the two-way version of pipe for a parent and child.

MapUnix socket address types
AF_UNIX address
  • Pathname
    • /run/app.sock
    • File permissions apply
    • unlink before bind
  • Abstract (Linux)
    • Leading NUL byte
    • No file to clean up
    • No permission bits
  • Unnamed
    • socketpair()
    • Two connected ends
    • Shared through fork

Stream, datagram and seqpacket

SOCK_STREAM behaves like TCP: a reliable, ordered byte stream with no message boundaries, so you must frame messages yourself, for example with newlines or a length prefix. SOCK_DGRAM keeps each message separate like UDP, but on Linux local datagrams are reliable and do not get reordered; a full receiver makes the sender block instead of dropping data. SOCK_SEQPACKET is connection-based like a stream but keeps message boundaries, which is often exactly what a request and reply protocol wants.

For a datagram server, clients that want replies must bind their own address too, otherwise the server has nowhere to send the answer. Stream sockets avoid this because the connection itself identifies the client.

Who is on the other end?

On Linux, connecting to a pathname socket needs write permission on the socket file and search permission on its directories. Put sockets in a directory such as /run/myapp with mode 750 and choose the group carefully. Remember that access to some sockets equals root access: anyone who can write to /var/run/docker.sock can start a privileged container.

The server can ask the kernel for the peer's credentials with getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len), which fills a struct ucred with pid, uid and gid (define _GNU_SOURCE). The kernel records these values at connect time, so the client cannot lie about them. Many daemons use this to allow root or one service user only.

  • ss -xp shows which process owns each Unix socket
  • struct ucred c; socklen_t l = sizeof c; getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &c, &l);
  • systemd socket units set ownership with SocketUser= and SocketMode=

Passing descriptors with SCM_RIGHTS

sendmsg can carry ancillary data next to normal bytes. With level SOL_SOCKET and type SCM_RIGHTS, the ancillary data is an array of file descriptors. The kernel does not copy the numbers; it installs new descriptors in the receiving process that refer to the same open files, with the same offsets and flags. The receiver's numbers are usually different from the sender's.

Send at least one byte of normal data together with the descriptors, and have the receiver pass MSG_CMSG_CLOEXEC to recvmsg so the new descriptors do not leak into its children. Uses include privilege separation (a small root helper opens a protected file and hands it over), handing a listening socket to a new version of a server for zero-downtime restarts, and passing memfd buffers between processes.

SequenceHanding over an open file
Helper (root)
Kernel
Worker (user)
  1. 1open("/etc/secret.conf") = fd 5
    Helper (root) to Kernel: open("/etc/secret.conf") = fd 5
  2. 2sendmsg with SCM_RIGHTS [5]
    Helper (root) to Kernel: sendmsg with SCM_RIGHTS [5]
  3. 3installs new fd 7, same open file
    Kernel to Worker (user): installs new fd 7, same open file
  4. 4read(7, ...) works without permission to open
    Worker (user) to Worker (user): read(7, ...) works without permission to open
  5. 5close(5): the worker's fd 7 stays valid
    Helper (root) to Kernel: close(5): the worker's fd 7 stays valid

Choosing an IPC mechanism

Start with the simplest tool that fits. A pipe is perfect when a parent feeds a child or reads its output in one direction. A Unix stream socket is the default for local client and server designs: two-way, many clients, permission control, peer credentials and descriptor passing, and the code moves to TCP easily if the service ever needs to go remote.

Choose a message queue when you want small, prioritised messages that survive the sender exiting. Choose shared memory only when you move a lot of data or need very low latency, and accept the extra work of locking and crash recovery. Many real systems combine them: a Unix socket for control messages and a shared memory buffer, passed as a memfd over that socket, for bulk data.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Create a stream socket on a path~35m
  2. 2
    Accept clients and exchange data~35m
  3. 3
    Compare stream and datagram modes~35m
  4. 4
    Pass descriptors with SCM_RIGHTS~35m
  5. 5
    Choose between pipes, sockets and shm~35m

Key points

  • Server: socket(AF_UNIX), bind to a path, listen, accept. Client: socket, connect.
  • unlink a stale socket path before bind, or bind fails with EADDRINUSE.
  • File permissions on the socket path control who may connect.
  • SCM_RIGHTS ancillary messages hand open descriptors to another process.

Key terms

Tap a card to flip it. 0/6 known

Examples

c
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
int main(void) {
  int s = socket(AF_UNIX, SOCK_STREAM, 0);
  struct sockaddr_un addr = { .sun_family = AF_UNIX };
  strncpy(addr.sun_path, "/tmp/demo.sock", sizeof addr.sun_path - 1);
  unlink(addr.sun_path);
  if (bind(s, (struct sockaddr *)&addr, sizeof addr) < 0) { perror("bind"); return 1; }
  listen(s, 8); int c = accept(s, NULL, NULL);
  write(c, "hello\n", 6); close(c); close(s);
  return 0;
}

Test it from another terminal with: nc -U /tmp/demo.sock

A client for the explainer's server

This client connects to /tmp/demo.sock and prints everything the server sends. Step 1: create an AF_UNIX stream socket. Step 2: fill sockaddr_un, copying the path safely with strncpy and room for the NUL. Step 3: connect; ENOENT means no socket file exists and ECONNREFUSED means the file exists but nobody listens. Step 4: read until the server closes the connection (read returns 0).

c
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
int main(void) {
  int s = socket(AF_UNIX, SOCK_STREAM, 0);
  if (s < 0) { perror("socket"); return 1; }
  struct sockaddr_un a = { .sun_family = AF_UNIX };
  strncpy(a.sun_path, "/tmp/demo.sock", sizeof a.sun_path - 1);
  if (connect(s, (struct sockaddr *)&a, sizeof a) < 0) { perror("connect"); return 1; }
  char buf[128]; ssize_t n;
  while ((n = read(s, buf, sizeof buf)) > 0) fwrite(buf, 1, (size_t)n, stdout);
  close(s); return 0;
}

Sending a file descriptor

This function sends one open descriptor over a connected Unix socket. Step 1: prepare one byte of real data, because some data must travel with the descriptor. Step 2: reserve a control buffer of CMSG_SPACE(sizeof(int)) bytes; the union keeps it correctly aligned. Step 3: fill the control message header with SOL_SOCKET and SCM_RIGHTS and copy the descriptor in with memcpy. Step 4: sendmsg. The receiver mirrors this with recvmsg and reads the new descriptor from CMSG_DATA.

c
int send_fd(int sock, int fd) {
  char byte = 'F';
  struct iovec iov = { .iov_base = &byte, .iov_len = 1 };
  union { char buf[CMSG_SPACE(sizeof(int))]; struct cmsghdr align; } u;
  memset(&u, 0, sizeof u);
  struct msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1,
                        .msg_control = u.buf, .msg_controllen = sizeof u.buf };
  struct cmsghdr *c = CMSG_FIRSTHDR(&msg);
  c->cmsg_level = SOL_SOCKET;
  c->cmsg_type = SCM_RIGHTS;
  c->cmsg_len = CMSG_LEN(sizeof(int));
  memcpy(CMSG_DATA(c), &fd, sizeof(int));
  return sendmsg(sock, &msg, 0) == 1 ? 0 : -1;
}

Quick reference

  • sun_path holds at most 108 bytes including the NUL; keep socket paths short
  • unlink the old socket path before bind, or bind fails with EADDRINUSE
  • ss -xlp lists listening Unix sockets and their processes
  • socketpair(AF_UNIX, SOCK_STREAM, 0, sv) is a two-way pipe for parent and child
  • SO_PEERCRED returns the peer's pid, uid and gid as recorded by the kernel
  • SCM_RIGHTS passes open descriptors; send at least one data byte with them
  • nc -U /path or socat - UNIX-CONNECT:/path is a quick test client
  • Abstract sockets start with a NUL byte and have no file or permissions

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A server crashed and now bind fails with EADDRINUSE on /run/app.sock. Why?

Question 2

2What does a process receive when another process sends it a descriptor with SCM_RIGHTS?

Question 3

3Which socket type keeps message boundaries and also uses connections?

Question 4

4How can a server reliably learn which user connected to its Unix socket?

Question 5

5Why is write access to /var/run/docker.sock considered equal to root access?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Run the explainer's server, connect with nc, then list the socket with ss and with ls -l.

  2. Exercise 2medium

    Use socketpair so a parent sends "ping" to a child and the child answers "pong" over the same pair.

  3. Exercise 3hard

    Extend a Unix socket server so it accepts a connection only if the client's UID is 0 or equal to the server's own UID, and closes it otherwise.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Are Unix sockets faster than TCP on localhost?
Usually yes, because they skip the TCP/IP stack: no checksums, no congestion control and no port handling. The exact gain depends on message size and workload.
Can Unix sockets work between two machines?
No, they work only within one host (or between containers sharing a mounted socket file). Use TCP for remote access.
Where should I put my service's socket file?
Under /run, for example /run/myapp/myapp.sock, which is a tmpfs cleared at boot. systemd's RuntimeDirectory= creates such a directory for you.
What is the difference between a socket file and a FIFO?
A FIFO is a one-way byte pipe shared by whoever opens it. A socket supports separate two-way connections per client, plus credentials and descriptor passing.

Go deeper

ShareXLinkedInWhatsApp