Network programming in Bash
Did you know that bash can connect to TCP/UDP servers on its own, without using nc
/telnet
(or even awk!)?
I learned this in the abyss of info bash
: it mentions that redirects like /dev/stdin
, /dev/fd/FD
, etc, are treated specially. One of redirections on the list was /dev/tcp/HOST/PORT
—I could not believe my eyes!
After figuring out how to use the same file descriptor for reading and writing, I was able to make a simple HTTP request to Google:
$ (exec 3<>/dev/tcp/www.google.com/80 ;
echo "GET /search?q=bash+madness HTTP/1.0" >&3;
echo >&3;
cat <&3 ) | less
Yes, it’s that simple.