A Unix socket (also called a Unix domain socket or IPC socket) is a special file used for inter-process communication (IPC) on Unix-like operating systems. It enables two processes running on the same machine to communicate efficiently without using network protocols like TCP/IP.
๐น Key Concepts of Unix Sockets #
- File-Based Communication:
- Unlike TCP/IP sockets, Unix sockets exist as special files in the filesystem (e.g.,
/tmp/mysocket
). - Processes read and write data to these files to exchange information.
- Unlike TCP/IP sockets, Unix sockets exist as special files in the filesystem (e.g.,
- Faster than TCP/IP Sockets:
- Since Unix sockets don’t use network layers, they offer lower latency and higher efficiency compared to network sockets.
- Two Main Types:
- Stream Sockets (
SOCK_STREAM
): Provides reliable, connection-based communication (like TCP). - Datagram Sockets (
SOCK_DGRAM
): Provides connectionless, unordered communication (like UDP).
- Stream Sockets (
- Permissions & Security:
- Since Unix sockets are represented as files, they inherit Unix file permissions, allowing fine-grained access control.
๐น How Unix Sockets Work #
- Creating a Socket: A server process creates a socket file in the filesystem.
- Binding & Listening: The server binds to the socket file and listens for incoming connections.
- Connecting: A client process connects to the socket file.
- Data Exchange: The server and client send and receive data.
- Closing the Connection: The socket is closed when communication is done.
๐น Example: Creating and Using a Unix Socket in Python #
import socket
import os
# Define socket file path
SOCKET_PATH = "/tmp/mysocket"
# Remove existing socket file if it exists
if os.path.exists(SOCKET_PATH):
os.remove(SOCKET_PATH)
# Create a Unix socket
server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server_socket.bind(SOCKET_PATH)
server_socket.listen(1)
print("Server is waiting for a connection...")
conn, _ = server_socket.accept()
# Receive and respond to messages
data = conn.recv(1024)
print("Received:", data.decode())
conn.sendall(b"Hello from server!")
# Cleanup
conn.close()
server_socket.close()
os.remove(SOCKET_PATH)
๐ This is a simple server that listens on a Unix socket, receives a message, and replies.
๐น When to Use Unix Sockets #
โ
When two processes on the same machine need to communicate efficiently
โ
For faster IPC than TCP/IP sockets
โ
To take advantage of file-based access control
๐ซ Not suitable for communication between different machinesโuse TCP/IP sockets instead.
Let me know if you want a more detailed example! ๐
No Responses