I'm trying to set up a minimal web server using netcat (nc). When the browser calls up localhost:1500, for instance, it should show the result of a function (date in the example below, but eventually it'll be a python or c program that yields some data). My little netcat web server needs to be a while true loop in bash, possibly as simple as this:
while true ; do echo -e "HTTP/1.1 200 OK\n\n $(date)" | nc -l -p 1500 ; done
When I try this the browser shows the currently available data during the moment when nc starts. I want the browser displays the data during the moment the browser requests it, though. How can I achieve this?
Type in nc -h and see if You have -e option available. If yes, You can create a script, for example:
script.sh
and run it like this:
Note that -e option needs to be enabled at compilation to be available.
Add
-q 1
to thenetcat
command line:The problem you are facing is that nc does not know when the web client is done with its request so it can respond to the request.
A web session should go something like this.
Lines that begin with "\n" are simply empty lines without even a space and contain nothing more than a new line character.
I have my bash httpd launched by xinetd, xinetd tutorial. It also logs date, time, browser IP address, and the entire browser request to a log file, and calculates Content-Length for the Server header response.
To add more functionality, you could incorporate.
Happy bashing!
Donno how or why but i manage to find this around and it works for me, i had the problem I wanted to return the result of executing a bash
NOTE: This command was taken from: http://www.razvantudorica.com/08/web-server-in-one-line-of-bash
this executes bash script test and return the result to a browser client connecting to the server running this command on port 8080
My script does this ATM
and my web browser is showing
simply amazing!
Another way to do this
Let's test it with 2 HTTP request using curl
In this example, 172.16.2.6 is the server IP Address.
Server Side
Client Side
If you want to execute another command, feel free to replace $(date).
Try this:
The
-c
makes netcat execute the given command in a shell, so you can use echo. If you don't need echo, use-e
. For further information on this, tryman nc
. Note, that when usingecho
there is no way for your program (thedate
-replacement) to get the browser request. So you probably finally want to do something like this:Where
yourprogram
must do the protocol stuff like handling GET, sending HTTP 200 etc.