How To Write To A Network Socket With Bash

You probably didn’t know but you can trivially open a network socket and communicate with a host by writing to:

/dev/<PROTO>/<HOST>/<PORT>

The protocol can be UDP or TCP and the host any internet connect machine including localhost.

Why is this useful?

It allows you to create scripts that, for example, grab a webpage and don’t rely on external tools like curl or telnet. This makes the scrip much more portable and you don’t need to run bunch of test to make sure your dependancies are present on the system.

Let’s create a script to grab the index.html page form this website:

#!/usr/bin/env bash
set -eu

exec 3<>/dev/tcp/"$1"/80

printf "GET /index.html HTTP/1.1\nHost: bash-prompt.net\n\n^]" >&3

cat <&3

Running this gives:

$ ./bash-index.sh bash-prompt.net
HTTP/1.1 301 Moved Permanently
Server: nginx/1.14.2
Date: Thu, 03 Dec 2020 15:32:35 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: https://bash-prompt.net/index.html
Strict-Transport-Security: max-age=15768000
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block

<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.14.2</center>
</body>
</html>

And that’s all there is to it!