4

I found a similar question here but there's no answer.

I wrote this script named answer.sh:

#!/bin/sh

echo "HTTP/1.1 200 OK

Hello World"

If I run

./answer.sh | nc -c -l -p 8797

and then browse to localhost:8797 I get a web page with only a "Hello World" text (that's exactly what I want).

but if i run

nc -l -p 8797 -e ./answer.sh

the browser says the connection was interrupted. So I try

nc localhost 8797

to see what happens and I get this:

HTTP/1.1 200 OK

Hello World
read(net): Connection reset by peer

I would like to understand what's going on and what are (technically) the difference between the working way and the other.

Thanks in advance.

1 Answer 1

1
+50

It looks like this question is going slow with answers. I'm not in a position to test with nc -e, so this isn't an entire answer, but will perhaps it will help start the conversation...

I recommend using a Content-Length: header in the HTTP response, e.g.

#!/bin/sh

echo "HTTP/1.1 200 OK
Content-Length: 11

Hello World"

When used in ...

./answer.sh | nc -l -p 8797

... I found it allowed a normal browser to complete the request. Without it the browser doesn't know when to stop reading the response, and will wait for the server end to close the connection.

When connecting from nc localhost 8797 as the client though, clearly this makes no difference. nc isn't interested in the HTTP headers, and will just keep reading until the server end drops the connection.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! This was the solution. I just tested it and it works. I also tried (just to see what happens) to set the Content-Length parameter to a lower or higher number (than the real number of chars). If I set it to a lower value the content is truncated at the number I choose, if I set it to a greater value it gives me the same error I got at the beginning (just wanted to test that). So! Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.