NetCat (nc) as a webserver
Recently, we needed to perform some tests in a network. Specifically, we wanted to check the configuration of a firewall and see what IP are blocked and/or which ports are allowed to go through. To do so, we used NetCat to setup a small web-server to perform our tests.
Netcat (often abbreviated to nc) is a computer networking utility for reading from and writing to network connections using TCP or UDP. Netcat is designed to be a dependable back-end that can be used directly or easily driven by other programs and scripts. At the same time, it is a feature-rich network debugging and investigation tool, since it can produce almost any kind of connection its user could need and has a number of built-in capabilities.
while true; do echo -e "HTTP/1.1 200 OK\r\n\r\n<h1>$(hostname) is live</h1>$(date)" | nc -vl -p 5555; done
or in one line
while true; do echo -e "HTTP/1.1 200 OK\r\n\r\n<h1>$(hostname) is live</h1>$(date)" | nc -vl -p 5555; done
Explanation of code:
- The above code creates an infinite loop that calls
ncin listening mode, we had to do this asncwill terminate as soon as it serves one client. - Using
echowe create anhtml200response along with a small “webpage”. - While generating the webpage,
echo -ewill execute the commandshostnameanddateto get the current system values adding them to the resulted text. - The resulted text is then piped to
ncto be served as a response to any incoming clients. - The date and time that
ncwill show to the client is not the current date and time when visiting the webpage but the one that was whenechowas executed.
nc parameters:
-v,--verboseSets the verbosity level and it can be used several times to increase it even further-l,--listenInstructsncto bind and listen for incoming connections (just like a web-server)-p,--source-portwithportparameter specifies the source port to be used bync


