How to Serve Content to the Web Browser?
We have successfully made a connection via TCP and made our Netcat web server respond to an incoming HTTP request. But till now, we are seeing just blank screens without any content. It’s time to finish building our minimal web server by enabling web content sharing in the form of HTML pages.
Let’s create a simple HTML page to be served. This can be done by creating a file called gfg.html on our machine. The path of this file can be arbitrary, but it is conventional to use the ‘/var/www/html ‘path in Linux to store web pages to be served by web servers. This is the default path used by the Apache web server.
Note: The file name for HTML page is arbitrary. But it should have the extension ‘.html’. In my case, it is gfg.html
Create a new file in the conventional location by entering the following command in the terminal.
sudo nano /var/www/html/gfg.html
- gfg.html
HTML
<!DOCTYPE html> < html > < head > < title >Minimal Web Server using Netcat</ title > </ head > < body style = "background-color: black;" > < h1 style = "color: green; text-align: center;" >w3wiki</ h1 > < h2 style = "color: white; text-align: center;" >Minimal Web Server using Netcat</ h2 > </ body > </ html > |
Copy and paste the above code in the newly created file – gfg.html. Press ‘CTRL+X’ and then ‘Y’ to save your changes using nano.
1. Serving the HTML page
Now, let’s use the already discussed concept of piping to pipe the HTTP response and our newly created HTML document as the input to our Netcat server. We can do this by typing the following command in the terminal.
{ echo -e 'HTTP/1.1 200 OK\r\n'; cat /var/www/html/gfg.html; } | netcat -l -p 8000
- In the command, we have used braces and semicolons to combine the echo and cat commands.
- The cat command, when one file is given as input, prints the content of the file as stdout which is fed as stdin to the netcat server, listening on port 8000.
- Thus, the content of the file – gfg.html will be served by our netcat server, which in turn, gets interpreted and rendered by the web browser as a web page to the client.
2. Viewing served content
While the Netcat server is listening, keep the terminal alive and open a web browser in another window. Connect to the Netcat web server by entering the already mentioned URL – http://localhost:8000/
The following web page will be loaded by the web browser.
Minimal Web Server Using Netcat
Netcat is a networking utility that can be used to complete various tasks over TCP and UDP. It can be used to send TCP and UDP packets, also it can listen on the ports, specified for UDP and TCP. This utility is well-known for its versatility, as its application ranges from setting up simple chat servers to building your reverse shell. The interesting part about this utility is that it can be used as a web server as HTTP also relies on TCP.
In this article, we will learn how to harness the power of Netcat to spin up a minimal web server in no time.