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:


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:\n\n^]" >&3

cat <&3

Running this gives:

$ ./
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
Strict-Transport-Security: max-age=15768000
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block

<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>

And that’s all there is to it!