Minimum HTTP server with netcat

Problem

Sometimes you need to have a simple HTTP server. You want to check connectivity from other machine or whatever sinister reason you can have.

Solution

We are going to create a simple HTTP server at port 8000.
You can use the netcat command:

nc -l -p 8000 -c 'echo -e "HTTP/1.1 200 OK\n\nHello $(id -un)\nCurrent time $(date)"

Then you can go to a web browser and write load the url at the port 8000

http://localhost:8000

But this works just for one connection, after that connection you must execute again the nc command, so to accept more connections you must add a while loop:

while [ 1 ];do nc -l -p 8000 -c 'echo -e "HTTP/1.1 200 OK\n\nHello $(id -un)\nCurrent time $(date)"'; done

May be you want to display a simple html file (with no images, ajax or any other HTML element that launchs more HTTP requests) like this one:

<!DOCTYPE html>
<html>
<body>
<h1>Example</h1>
This is a simple<br/>
webserver running with
<b>nc</b>
</body>
</html>

Let’s suppose that you have your html saved in a file called index.html, then you can show it in your netcat server as follows:

while [ 1 ];do nc -l -p 8000 -c 'echo -e "HTTP/1.1 200 OK\n";cat index.html'; done

If you are not able to connect to your netcat server may be you have activated iptables, take a look writing as root:

iptables -L

If you want to remove the iptables that can be blocking this requests write the following commands as root:

iptables -F
iptables -X
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT

Sharing Internet connection from your Linux

I want to share my Interent connection from my linux to another equipment.

First you have to enable NAT in your linux,
as root you must type:

# iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE

Then, logged as root, you have to enable IP forwarding.
There are two ways:

# sysctl -w net.ipv4.ip_forward=1

or

# echo 1 > /proc/sys/net/ipv4/ip_forward

Now you have to configure in your other device the IP of your linux as default gateway.

And that’s all folks!

If you have problems with iptables and you want to remove all the rules write:

iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT