Linux / Unix - Sockets
Unix Domain Sockets vs Internet Domain Sockets
- Unix Domain Sockets: a.k.a. IPC sockets, allow communication between 2 processes, i.e. the server and the client, on the same machine.
- use the file system as the address space (everything in Unix is a file) e.g.
/var/run/docker/containerd/containerd.sock
- use the file system as the address space (everything in Unix is a file) e.g.
- Internet Domain Sockets: allow communication over a network, i.e. the server and the client are on different machines.
- use the IP address and a port number as socket address, e.g.
10.20.30.40:4444;
- use the IP address and a port number as socket address, e.g.
As you can see from the system call below, they are distinguished by the domain.
Communication
Two processes may communicate with each other if each obtains a socket.
- The server process binds its socket to an address, opens a listen channel, and then continuously loops.
- Inside the loop, the server process is put to sleep while waiting to accept a client connection.
- Upon accepting a client connection, the server then executes a read system call that will block wait.
- The client connects to the server's socket via the server's address.
- The client process then writes a message for the server process to read.
At different architectural levels:
- Unix Domain Sockets (
AF_UNIX): Data buffers are transferred directly within kernel memory between process address spaces, bypassing the network interface, packetization, checksumming, and routing logic entirely. - Internet Domain Sockets (
AF_INET/AF_INET6): Data packets traverse the operating system transport layer (TCP/UDP) and the network layer (IP), enabling transparent communication across physical networks.
What Makes a Socket: Socket vs. General File Descriptor I/O
In Unix philosophy, "everything is a file" is often misconstrued to mean that every file descriptor behaves like a regular file on disk. Sockets demonstrate both the elegance and the explicit boundaries of the file descriptor abstraction.
You Cannot open() a Socket (The ENXIO Rule)
When you list a Unix domain socket file on disk (such as Docker's /var/run/docker.sock or a local database socket), you see a filesystem inode marked with the s type bit:
ls -l /var/run/docker.sock
# Output:
# srw-rw---- 1 root docker 0 Oct 19 12:00 /var/run/docker.sock
Because it visibly exists as an entry in the filesystem hierarchy, developers sometimes wonder: Can I open it with standard file I/O?
// THIS WILL FAIL!
int fd = open("/var/run/docker.sock", O_RDWR);
Calling open(2) on a Unix domain socket file fails with errno == ENXIO (No such device or address).
POSIX and the Linux VFS deliberately forbid open() on socket inodes. Regular file open() simply establishes an offset pointer to a storage inode. A socket, by definition, represents an active, two-way communication channel that requires protocol state negotiation (binding, listening, or connecting to a peer process)—none of which the file-oriented open() syscall can initiate.
How a Socket FD Is Born: Socket-Producing Syscalls
You cannot obtain a socket file descriptor by opening a file path. A socket descriptor enters a process's file table only through a specialized set of socket-producing system calls:
socket(): Allocates an unbound, unconnected socket endpoint with a protocol family (AF_INET,AF_UNIX).socketpair(): Creates an interconnected pair of unnamed local sockets in a single atomic step.accept()/accept4(): Extracts a completed connection from a listening socket's backlog queue and returns a brand-new connected socket file descriptor.recvmsg()withSCM_RIGHTS: Receives an open socket descriptor passed across process boundaries through Socket Control Messages (SCM).- Descriptor Cloning (
dup(),dup2(),fcntl(F_DUPFD)): Duplicates an existing socket descriptor slot within the process file table. - Inheritance across
fork(): Inherits active socket descriptors from the parent process into the child (unlessSOCK_CLOEXECwas configured). pidfd_getfd(): Clones a socket file descriptor from an arbitrary target process via its PID descriptor (Linux 5.6+).
Socket FD vs. Regular File Descriptor I/O
While both sockets and regular files use integer file descriptors (fd), their underlying kernel data structures and behavioral semantics diverge significantly:
| Dimension | Regular File Descriptor | Socket File Descriptor |
|---|---|---|
| Creation | open(), openat(), creat() |
socket(), socketpair(), accept4() |
| Kernel Representation | struct file pointing to struct inode + page cache / block device |
struct file pointing to struct socket + struct sock + network stack |
| Seeking & Offsets | Stateful file offset (lseek() works) |
Unseekable stream/datagram (lseek() fails with ESPIPE) |
| EOF Semantics | Byte offset reaches storage boundary (read() = 0) |
Remote peer sent FIN / half-closed write end (read() = 0) |
| Truncation & Mapping | Supports ftruncate(), fallocate(), and mmap() |
Fails with EINVAL or ENODEV |
| Specialized Syscalls | File locks (flock, fcntl), direct I/O (O_DIRECT) |
send(), recv(), setsockopt(), shutdown() (Calling these on a file fails with ENOTSOCK) |
Event Readiness (epoll) |
Always reported as immediately ready (regular disk I/O blocks synchronously in kernel, never polls) | True asynchronous readiness (notifies when network buffers fill or drain) |
Core System Calls Reference
The Linux Berkeley Sockets API is divided into three functional families:
Linux Sockets System Call Taxonomy:
1. Lifecycle & Connection Setup
socket() ──► bind() ──► listen() ──► accept4() ──► connect() ──► shutdown()
[Detailed Guide: Socket Lifecycle Syscalls](/en/linux/syscalls/socket/)
2. Data Transmission & Messaging
send() / recv() ──► sendto() / recvfrom() ──► sendmsg() / recvmsg() ──► recvmmsg()
[Detailed Guide: Socket I/O Syscalls](/en/linux/syscalls/send-recv/)
3. Configuration & Introspection
setsockopt() ──► getsockopt() ──► getsockname() ──► getpeername()
[Detailed Guide: Socket Options & Introspection](/en/linux/syscalls/setsockopt/)
1. Socket Lifecycle Syscalls
These system calls establish, manage, and tear down communication endpoints:
socket(): Allocates a new socket file descriptor. Modern Linux allows specifyingSOCK_NONBLOCKandSOCK_CLOEXECdirectly in thetypeparameter to eliminate race conditions and extrafcntl()calls.socketpair(): Instantly creates an interconnected pair of unnamed bidirectional Unix domain sockets (sv[0]andsv[1]), widely used for parent-child IPC.bind(): Assigns a local address to a socket—either an IPv4/IPv6 port (struct sockaddr_in) or a filesystem path (struct sockaddr_un). Specifying port0binds to a dynamic ephemeral port.listen(): Marks a socket as passive. Manages the kernel SYN Queue (half-open handshakes) and Accept Queue (completed handshakes, bounded bybacklogand/proc/sys/net/core/somaxconn).accept()/accept4(): Dequeues an established connection from the Accept Queue and returns a brand new connected file descriptor.accept4()appliesSOCK_NONBLOCKandSOCK_CLOEXECatomically.connect(): Initiates an active connection (TCP 3-way handshake) to a remote server. On non-blocking sockets, returns-1withEINPROGRESS, enabling event monitoring via epoll.shutdown(): Performs directional TCP half-close (SHUT_RD,SHUT_WR,SHUT_RDWR). Unlikeclose()(which only decrements the process descriptor reference count),shutdown()immediately terminates protocol transmission.
2. Socket I/O & Messaging Syscalls
While standard read() and write() work on sockets, dedicated socket I/O calls provide vital protocol-level controls:
send()/recv(): Stream I/O with specialized flags:MSG_NOSIGNAL: Prevents fatalSIGPIPEprocess termination when writing to a closed peer.MSG_DONTWAIT: One-shot non-blocking I/O without modifying descriptor state.MSG_PEEK: Reads buffered data without consuming it.
sendto()/recvfrom(): Essential for connectionless UDP datagrams (SOCK_DGRAM), routing to destination addresses and capturing sender origins.sendmsg()/recvmsg(): Combines scatter-gather vectored I/O (struct iovec) with Ancillary Control Messages (struct msghdr/cmsg). The foundational mechanism for:- Passing open file descriptors across processes via
SCM_RIGHTS. - Verifying caller credentials (PID, UID, GID) via
SCM_CREDENTIALS. - Hardware packet timestamps via
SO_TIMESTAMP. - Deep dive: struct msghdr vs. struct cmsghdr (envelope vs. control payload memory layouts).
- Passing open file descriptors across processes via
sendmmsg()/recvmmsg(): Transmits or receives arrays of messages in a single system call, eliminating hundreds of thousands of context switches in high-PPS network services (DNS, QUIC).
3. Socket Options & Introspection
Tuning protocol behaviors and querying socket metadata:
setsockopt()/getsockopt():SO_REUSEADDR: BypassesTIME_WAITport collision on rapid server restarts.SO_REUSEPORT: Enables multiple worker processes to bind to the identical port, with the kernel distributing incoming connections across independent listener queues.TCP_NODELAY: Disables Nagle's algorithm to eliminate 40ms–200ms latency spikes in interactive RPCs (gRPC, Redis).SO_KEEPALIVE: Probes dead connections over silent network paths.
getsockname()/getpeername(): Introspects local bound addresses and remote connected peer IPs.
Connection Flow Summary
- Server-Side Lifecycle:
socket()→bind()→listen()→accept4()→recv()/send()→close(). - Client-Side Lifecycle:
socket()→connect()→send()/recv()→close(). - Network Cheat Sheet: See Shell Cheatsheet - Networking for CLI diagnostic tools (
ss,netstat,ip,lsof).
Code Examples
A Unix Domain Socket (often just called a Unix Socket) allows two processes on the same machine to talk to each other.
Unlike TCP/IP sockets (which use an IP address and Port), Unix sockets use a File Path on the filesystem. This makes them faster and more secure for local communication because they bypass the network stack entirely.
Here is a clear example using Python, followed by how to test it with command-line tools.
1. The Python Server (The Listener)
This script creates a socket file at /tmp/demo.sock and waits for a message.
# server.py
import socket
import os
# 1. Define the file path for the socket
SOCKET_PATH = "/tmp/demo.sock"
# 2. Cleanup: Make sure the file doesn't already exist
if os.path.exists(SOCKET_PATH):
os.remove(SOCKET_PATH)
# 3. Create the socket
# AF_UNIX = Unix Domain Socket (Local)
# AF_INET = Internet Socket (IP)
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# 4. Bind to the file path
server.bind(SOCKET_PATH)
# 5. Listen for incoming connections
server.listen(1)
print(f"Listening on {SOCKET_PATH}...")
try:
while True:
# Accept a connection
connection, client_address = server.accept()
try:
print("Connection accepted!")
# Read data
data = connection.recv(1024)
if data:
print(f"Received: {data.decode()}")
# Send a response back
response = f"Processed: {data.decode()}"
connection.sendall(response.encode())
finally:
# Clean up the connection
connection.close()
finally:
# Clean up the socket file when server stops
server.close()
os.remove(SOCKET_PATH)
2. The Python Client (The Sender)
This script connects to that specific file path and sends data.
# client.py
import socket
import sys
SOCKET_PATH = "/tmp/demo.sock"
# 1. Create the socket
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
# 2. Connect to the server's file path
print(f"Connecting to {SOCKET_PATH}...")
client.connect(SOCKET_PATH)
# 3. Send data
message = "Hello from Unix Socket!"
client.sendall(message.encode())
# 4. Receive response
data = client.recv(1024)
print(f"Server replied: {data.decode()}")
finally:
client.close()
3. How to verify it works (The "Aha!" Moment)
Step A: Run the Server
Open a terminal and run the server. It will hang, waiting for a connection.
python3 server.py
# Output: Listening on /tmp/demo.sock...
Step B: Look at the file system
Open a second terminal. You will see the socket actually exists as a file. The s at the start of the permissions line indicates it is a socket.
ls -l /tmp/demo.sock
# Output:
# srwxr-xr-x 1 user group 0 Jan 20 10:00 /tmp/demo.sock
Step C: Connect using netcat (No Python needed)
You can use the standard tool nc (netcat) with the -U flag to talk to Unix sockets directly.
echo "Hello from Netcat" | nc -U /tmp/demo.sock
# Output:
# Processed: Hello from Netcat
Key Differences in Code: TCP vs. Unix
The code is almost identical, except for two lines:
| Feature | TCP Socket (Standard) | Unix Domain Socket (Optimized) |
|---|---|---|
| Family | socket.AF_INET |
socket.AF_UNIX |
| Address | ("127.0.0.1", 8080) |
"/tmp/demo.sock" |
| Cleanup | OS frees port automatically | You must delete the file (rm) |
| Permissions | Hard to restrict (iptables) | Easy (Standard file chmod 700) |
When should you use this?
- Docker/Kubernetes: When you mount the Docker socket (
/var/run/docker.sock) into a container, you are using this exact mechanism to let the container talk to the host daemon. - Database Connections: connecting to PostgreSQL or Redis locally via Unix Socket is often 20-30% faster than connecting via
localhost:5432because it skips the TCP overhead.
What Sockets Do Not Replace: Specialized Linux IPC Primitives
While Unix Domain Sockets are the standard choice for bidirectional, credential-verified, and capability-sharing local IPC, they are not always the optimal primitive. Linux offers several specialized IPC mechanisms designed for specific constraints where sockets introduce unnecessary overhead:
Linux IPC Decision Guide:
Need network traversal or descriptor passing? ──► Sockets (Unix / TCP)
Need nanosecond zero-copy memory sharing? ──► Shared Memory + Futexes (memfd_create, mmap)
Need simple unidirectional pipeline? ──► Pipes (pipe)
Need 8-byte event signaling or counters? ──► Eventfd (eventfd)
Need kernel-persisted priority queues? ──► POSIX / SysV Message Queues (mq_overview)
1. Shared Memory + Futexes (mmap(MAP_SHARED), memfd_create, Semaphores)
- When to use: When two processes require zero-copy, nanosecond-scale data sharing without incurring a kernel system call on every read or write.
- How it works: Both processes map the exact same physical RAM pages into their virtual address spaces. Coordination is handled in user space using atomic variables and
futex()(Fast Userspace Mutex) or POSIX semaphores. - Why sockets fall short: Sockets copy data from user space into kernel socket buffers (
sk_buff), then copy it again into the receiving process's user memory (2 memory copies + 2 context switches per message). For high-frequency trading (HFT), high-resolution video frames (Wayland compositors), or huge tensor sharing between AI inference workers, shared memory is orders of magnitude faster. - Modern pairing: Daemons frequently create an anonymous memory buffer via
memfd_create(), pass its file descriptor to another process over a Unix socket viaSCM_RIGHTS, and both sides callmmap(MAP_SHARED).
2. Pipes, Eventfd, and Signalfd (pipe, eventfd, signalfd)
- When to use: Lightweight unidirectional streams or event notifications with far less setup ceremony than sockets.
pipe(): Ideal for unidirectional byte streams between parent and child processes (the foundation of shell pipelines likeps | grep). Zero addressing setup, no binding, and automatic EOF propagation when the write end closes.eventfd(): A lightweight 8-byte integer counter maintained by the kernel. Ideal for waking up anepollevent loop from another thread or kernel subsystem (e.g., KVM vhost interrupts) with virtually zero memory footprint.signalfd(): Converts asynchronous Unix signals (SIGCHLD,SIGTERM,SIGHUP) into synchronous file descriptor read events, eliminating the complexity of signal handler race conditions in modern event loops.
3. POSIX and System V Message Queues (mq_overview)
- When to use: When processes need a kernel-persisted, priority-ordered queue where messages are discrete records rather than an unstructured byte stream.
- Key advantage over sockets: Sockets require an active receiving process listening at the moment of transmission (or connections will be refused). Message queues are persistent kernel objects: a producer can post 1,000 prioritized messages into the queue before the consumer process even launches.
- epoll vs io_uring
- eBPF vs LKM
- eBPF vs cBPF
- execve vs fexecve vs execveat
- fd vs inode
- file vs dentry
- initrd vs initramfs
- pid vs tgid
- Process FD Table vs Global Open File Table
- Tracepoints vs Tracing Tools
- vmlinux vs vmlinuz
- pthread vs kthread
- pthread vs vfork
- seccomp vs landlock
- execve vs mmap
- shmem vs tmpfs
- stat vs fstat vs statx
- msghdr vs cmsghdr

