Socat
Install socat with Homebrew or MacPorts and create a pair of connected virtual serial ports for testing serial communication.
2 min readUpdated
socat (“SOcket CAT”) relays data between two endpoints of almost any kind: files, pipes, TCP and UDP sockets, serial devices and pseudo-terminals. A common use is a pair of virtual serial ports that are connected to each other. One program writes to one end and the other reads from the other end, which lets you test serial communication software without hardware or a null-modem cable.
Install socat
On macOS with Homebrew:
brew install socatWith MacPorts:
sudo port install socatOn Debian or Ubuntu:
sudo apt install socatCreate a pair of virtual serial ports
This command creates two pseudo-terminals (PTYs) and copies everything written to one into the other, in both directions:
socat -d -d pty,raw,echo=0 pty,raw,echo=0-d -dprints notice messages, including the names of the devices socat created.ptycreates a new pseudo-terminal for each side.rawpasses the data through without line editing or character translation.echo=0turns off local echo, so data is not sent back to the writer.
socat prints the two device names and keeps running until you stop it with Ctrl+C:
2014/08/07 01:40:56 socat[74896] N PTY is /dev/ttys0012014/08/07 01:40:56 socat[74896] N PTY is /dev/ttys0022014/08/07 01:40:56 socat[74896] N starting data transfer loop with FDs [3,3] and [5,5]On macOS the devices are named /dev/ttysNNN; on Linux they appear as /dev/pts/N. The numbers change on every run.
Recent socat versions mark raw as obsolete and recommend rawer, which also turns off echo: socat -d -d pty,rawer pty,rawer.
To get fixed names that you can put in a program’s configuration, add link= to each side. socat creates a symbolic link to each PTY:
socat -d -d pty,raw,echo=0,link=/tmp/ttyV0 pty,raw,echo=0,link=/tmp/ttyV1Test the connection
Open a new terminal and read from the first port:
cat /dev/ttys001Open another terminal and write to the second port:
echo "Hello World" > /dev/ttys002The first terminal prints “Hello World”. Replace the device names with the ones socat printed.
The PTYs belong to the user who started socat, so sudo is not needed. It would not help with the redirection either: in sudo echo "Hello World" > /dev/ttys002 the shell opens the device before sudo runs.