Serving Files with NetCat

Learn NetCat combined with shell scripting.

We'll cover the following

Using NetCat with scripting

We can use netcat to serve files if we combine it with a little bit of shell scripting. Let’s create a file called hello.txt with some text:

$ echo "This is a text file served from netcat" > hello.txt

Now, we execute this command to make netcat listen for connections on port 8000 and serve the hello.txt file:

$ while true; do nc -l 8000 < hello.txt; done

This loops indefinitely, listening for connections on port 8000, and then reads in the file, sending its contents to anything that connects. Let’s make a request with curl:

$ curl --http0.9 localhost:8000

HTTP0.9 is a headerless response, which is why we have to specify a --http0.9 flag to make sure curl handles it normally.

Use the terminal below to practice these commands.

Get hands-on with 1400+ tech skills courses.