The /dev/tcp device that isn't there
/ 1 min read
Apparently, my ping rabbit hole has a sequel. I needed to check whether a service was reachable from a machine without nc, and discovered that this works:
timeout 3 bash -c ': > /dev/tcp/example.com/443' \ && echo "open" \ || echo "closed or unreachable"The best part is that /dev/tcp does not exist:
$ ls /dev/tcpls: cannot access '/dev/tcp': No such file or directoryIt isn’t a Linux device at all. It is a small piece of Bash magic: when Bash sees /dev/tcp/host/port in a redirection, it opens a TCP socket instead of a file. If the connection succeeds, the command succeeds too.
And because it is a redirection, you can send data through it too. Here’s a tiny HTTP client made entirely out of Bash built-ins:
exec 3<>/dev/tcp/example.com/80printf 'GET / HTTP/1.0\r\nHost: example.com\r\n\r\n' >&3cat <&3exec 3>&-3<> opens the socket for both reading and writing; after that, file descriptor 3 behaves much like any other file. Not a replacement for curl, admittedly, but much more fun to stumble across.
Tiny, useful and delightfully fake. Linux makes everything look like a file; Bash is apparently happy to invent a few extra ones.