
HowTo: Virtual Serial Ports on Linux using socat, and more
June 9, 2009socat (SOcket CAT) – multipurpose relay – is a command line based utility that establishes two bidirectional byte streams and transfers data between them.
socat is #4 on the Top 100 Network Security Tools list, available in most distro repositories (on Debian/Ubuntu sudo apt-get install socat does the trick), really light on resources, and very efficient.
Sounds simple, does wonders!
Sidenote: socat is actually #71 on the mentioned list, but since socat is a much enhanced version of netcat, which is #4, it seems to me logical to count socat as #4 also.
One of the wonders you can do is creating pairs of “virtual” ports/interfaces/sockets etc., even hybrid pairs like port-socket, etc., where one (or both) ends of the pair can also be real objects. See socat man page for more details.
Creating pairs of virtual serial ports (VSP), is quite often wanted feature, yet it’s hard to find a solution online (try Googling it)… Pair of VSP’s is very useful to have esp. if you’re into embedded device programming, where many embedded development kits support debugging via serial link – PharLap in my case. Yes, it does have Ethernet debugging since ETS 14, but it’s a very unstable option.
Even if you’re using Ethernet debugging, it’s often much easier to have your embedded system in a virtual machine (VirtualBox, VMWare etc.), and do the debugging via virtual NIC.
To cut the talk short, many thanks to Gerhard Rieger, author of socat, for the following tips!
To create a pair of VSP’s
socat -d -d pty,raw,echo=0 pty,raw,echo=0
and that’s it! As long as the socat is running, you have a pair of VSP’s open (their names are printed by socat on initialization). See socat man page for more details on what the above command does.
Connecting executable and VSP
socat -d -d pty,raw,echo=0 "exec:myprog ...,pty,raw,echo=0"
where the executable myprog will be connected with the VSP through stdio.
Virtual network interfaces
In a similar fashion, you can create pairs of virtual network interfaces – tun/tap devices (again, this pair exists as long as the master process – socat – is alive):
sudo socat -d -d tun:10.0.0.1/8 tun:192.168.0.1/24
Yes, that’s it, you’ve got a pair of virtual network interfaces!
