Socat (SOcket CAT) is a powerful command-line tool that establishes bidirectional data channels between various sources and destinations. It acts as a relay, enabling data to flow between processes, files, devices, and network sockets. Think of it as a multi-purpose adapter that connects disparate communication channels.
Core Uses of Socat
-
Networking and Tunneling:
-
Create TCP/UDP listeners and connect them to other hosts/ports.
-
Forward local ports to remote servers (port forwarding).
-
Establish encrypted tunnels (e.g., with OpenSSL) over insecure networks.
-
Create virtual serial ports over TCP/IP connections.
-
Debugging and Testing:
-
Capture and analyze network traffic between applications.
-
Simulate network conditions (latency, packet loss).
-
Inject test data into applications.
-
Inter-Process Communication (IPC):
-
Transfer data between unrelated processes using standard input/output.
-
Create named pipes (FIFOs) and communicate through them.
-
File Manipulation:
-
Read from or write to files, including over the network.
-
Concatenate and transform data streams.
Socat Command Structure
socat [OPTIONS] <ADDRESS1> <ADDRESS2>OPTIONS: Control socat’s behavior (e.g., logging, timeouts, etc.).
-
ADDRESS1: The source address (e.g., TCP port, file, named pipe). -
ADDRESS2: The destination address (e.g., another TCP port, file). -
Simple TCP Relay:
socat TCP-LISTEN:8080,fork TCP:www.example.com:80This listens on port 8080 and forwards connections to www.example.com[www.example.com](https://www.example.com) on port 80.
- Create a Virtual Serial Port:
socat -d -d PTY,link=/dev/ttyS10 TCP:192.168.1.100:2000This creates a pseudo-terminal (/dev/ttyS10) that communicates over TCP.
- Debug Network Traffic:
socat -x -v TCP-LISTEN:8080,fork SYSTEM:"tcpdump -s 0 -w capture.pcap"Captures network traffic on port 8080 and saves it to a capture.pcap file.
- Inter-Process Communication:
socat -u EXEC:"producer_app",stderr EXEC:"consumer_app"Pipes the standard error output of producer_app to the standard input of consumer_app.
Flow Control
Socat lets you control the rate at which data flows between addresses, which is essential when connecting systems with different processing speeds or when simulating network conditions.
-u(Unidirectional): Forces data to flow only from the first address to the second.
socat -u TCP-LISTEN:9000,fork OPEN:/dev/null # Discard incoming data-U(Unidirectional Reverse): Forces data to flow only from the second address to the first.
socat -U EXEC:"generate_data.sh" TCP:192.168.1.10:8888 # Send script output to a remote host-b(Buffer Size): Sets the buffer size for data transmission.
socat -b 1024 TCP4-LISTEN:8080,fork TCP4:www.example.com:80 # 1KB buffer2. Data Transformation
The system address type is a powerful tool for transforming data on the fly using external commands.
socat TCP-LISTEN:8080,fork SYSTEM:"sed 's/foo/bar/g'" # Replace 'foo' with 'bar' in incoming data3. Logging
Socat provides detailed logging options to help troubleshoot connections and track data flow.
-
-d(Debug): Enable debugging output with varying levels (-d,-d -d, etc.). -
-lf: Log to a specified file. -
-v(Verbose): Increase the level of detail in log messages.
socat -v -lf socat.log TCP-LISTEN:8080,fork TCP:www.example.com:804. Timeouts
Set timeouts to gracefully handle connection failures and idle connections.
-
-T(Connection Timeout): Timeout for establishing a connection. -
-t(Activity Timeout): Timeout for inactivity on an established connection.
socat -T 10 -t 60 TCP-LISTEN:8080,fork TCP:www.example.com:805. Advanced Address Types
Socat supports a wide array of address types beyond just TCP and files:
-
OPENSSL: Establish encrypted connections. -
EXEC: Execute external commands. -
GOPEN: Open files in read/write mode. -
SCTP: Stream Control Transmission Protocol. -
UNIX: Unix domain sockets. -
…and many more: Refer to the
socatmanual for a complete list.
Example: OpenSSL Encryption
socat OPENSSL-LISTEN:4433,cert=server.crt,key=server.key,verify=0,fork TCP:localhost:80This creates a secure, encrypted tunnel to localhost on port 80, using the specified certificate and key.
Tips and Gotchas
-
Security: Be cautious with port forwarding and tunneling. Secure your connections (e.g., with SSH tunneling or SSL).
-
Resource Management: The
forkoption creates a new process for each connection. Use it judiciously to avoid resource exhaustion. -
Debugging: The
-d(debug) and-x(hexdump) options are invaluable for troubleshooting. -
Address Types: Socat supports a vast array of address types. Refer to the manual for details.
Real-World Gotcha: The fork Option and File Descriptor Limits
Here’s a scenario that’ll bite you at 2 AM. You set up socat as a TCP relay with fork to handle multiple connections, things work fine in testing, and then in production it falls over with cryptic errors. Nine times out of ten, you’ve hit your system’s open file descriptor limit.
Every forked child process inherits open sockets from the parent, and socat holds those descriptors open longer than you’d expect. On a default Linux system, the soft limit per process is 1024. If you’re relaying a moderately busy service — say, a container health check endpoint getting hammered — you’ll chew through those fast.
Check your current limits:
ulimit -n# typical output: 1024For a long-running socat relay, bump it before launching:
ulimit -n 65535socat TCP-LISTEN:8080,fork,reuseaddr TCP:backend-host:8080Or do it properly with a systemd unit so it survives reboots:
[Unit]Description=Socat TCP relayAfter=network.target
[Service]ExecStart=/usr/bin/socat TCP-LISTEN:8080,fork,reuseaddr TCP:backend-host:8080Restart=alwaysLimitNOFILE=65535
[Install]WantedBy=multi-user.targetEnable and start it:
systemctl daemon-reloadsystemctl enable --now socat-relayThe reuseaddr option on the listener is equally important — without it, restarting socat leaves the port in TIME_WAIT and you get “address already in use” for up to 60 seconds. Nobody wants to stare at that while trying to roll a fix. Always include reuseaddr on persistent listeners.