What are Unix Domain Sockets and How They Work

When we think about communication between applications, we often imagine TCP or UDP over the network. But sometimes, processes don’t need to leave the machine at all. That’s where Unix Domain Sockets (UDS) come in.

What is a Unix Domain Socket?

A Unix Domain Socket is a special type of inter-process communication (IPC) mechanism in Unix-like systems. Instead of using IP addresses and ports, processes talk to each other via a file path on the filesystem (e.g., /var/run/docker.sock).

In short:

  • TCP/UDP → communication over network
  • UDS → communication inside the same host

How it Works

  • UDS creates a socket file in the filesystem.
  • Processes can connect() to that file and exchange data.
  • It uses the same API as network sockets, but it’s faster and more secure because it doesn’t leave the kernel.

Example: Docker CLI communicates with the Docker Daemon via /var/run/docker.sock.

Types of Unix Domain Sockets

  1. Stream sockets – similar to TCP, reliable and connection-oriented.
  2. Datagram sockets – similar to UDP, message-based and connectionless.

Example in Python

import socket
import os

server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
socket_path = "/tmp/uds_example.sock"

if os.path.exists(socket_path):
    os.remove(socket_path)

server.bind(socket_path)
server.listen(1)

print("Server is listening...")
conn, _ = server.accept()
print("Received:", conn.recv(1024).decode())

Client

import socket

client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.connect("/tmp/uds_example.sock")
client.sendall(b"Hello via UDS")

Why It Matters

  • Performance: Faster than TCP/UDP for local communication.
  • Security: Access can be restricted via file permissions.
  • Simplicity: No need for IP/port configuration.