Single Line Web Server With nc on FreeBSD
I wrote a single file web server in my last post about Getting Started With tor Hidden Services on FreeBSD. I figured it might be useful to have a couple of variations of simple web servers in their own post. This post covers single line and single file web servers with nc on FreeBSD. Content served from a static file or a script is presented.
UPDATE: A follow up post exists. A Better Scripted Netcat Server
Software Versions
Instructions
First, add the following to index.html so we have a file to serve.
The netcat Wikipedia page lists a one-line one-shot web server. It has been adapted for FreeBSD below.
The server body can be put in a loop to serve the file multiple times. The host and port definitions have been moved to the beginning of the line in the version below.
The above line is complicated enough that it might want live in a file, like server.sh. A content type definition has been moved to the beginning of the file. A body and response have been defined. A couple of useful headers have been added. Finally, the response number is echoed before each response.
Make the server script executable before running it.
By redefining the body clause, the script can serve dynamic content. A simple JSON date server is listed below.
A one line version of the JSON date server is listed below.
A one line version of the single file web server is listed below.
Either of the following lines can be used to test the server from the command line. date is piped into nc so the client will send EOF to the server. The server will also log something to the terminal this way.
Note that these servers are not necessarily robust. They may trip up clients that do not close the connection.
References:
- Bash, How to assign a heredoc value to a variable in Bash?
- Bash, The while loop
- Bash, Length of string in bash
- Bash, Command Substitution
- FreeBSD, Man nc
- FreeBSD Forums, nc Server Not Disconnecting
- FreeBSD, Getting Started With tor Hidden Services on FreeBSD
- HTML, Coding An HTML 5 Layout From Scratch
- HTML, The Complete List of MIME Types
- HTML, W3C Markup Validation Service
- UNIX, Simple command line http server
- UNIX, One command line web server on port 80 using nc (netcat)
- UNIX, Faking Services using Netcat (For Testing Nagios)
- Wikipedia, Netcat: Setting up a one-shot webserver on port 8080 to present the content of a file