2

I have the following command:

echo 'HTTP/1.1 200 OK\r\n' | nc -l -p 8000 -c

and when I curl localhost:8000 I am not seeing HTTP/1.1 200 .. being printed.

I am on mac os x with netcat 0.7.1

Any ideas?

#!/bin/bash

trap 'my_exit; exit' SIGINT SIGQUIT

my_exit()
{
        echo "you hit Ctrl-C/Ctrl-\, now exiting.."
        # cleanup commands here if any
}

if test $# -eq 0 ; then
        echo "Usage: $0 PORT"
        echo ""
        exit 1
fi

while true
do
        echo "HTTP/1.1 200 OK\r\n" | nc -l -p ${1} -c
done

and testing with:

curl localhost:8000

2
  • no error messages. @Cyrus
    – Tinker
    Aug 21, 2014 at 21:00
  • 1
    Have you checked the console output when you run the echo without a pipe? Aug 21, 2014 at 23:55

3 Answers 3

4

Your approach has multiple issues.

Escape sequences

The escape sequences are not honored unless you use the -e switch.

echo -e 'HTTP/1.1 200 OK\r\n'

Without -e, you are sending the backslashes and letters verbatim. The above forms a full HTTP status line.

Protocol

The status line alone does not constitute a response. The format requires two CRLFs

  1. One as part of the Status Line itself
  2. One to terminate the respnse header

Try this

echo -e 'HTTP/1.1 200 OK\r\n\r\n'

netcat invocation

The -c flag is plain wrong, because it expects a command argument.

echo -e 'HTTP/1.1 200 OK\r\n\r\n' | nc -l -p $port

Content

Even with that, curl will block after receiving the reply, because it's waiting for the server to supply a body. You could either send more data to nc, or choose a more appropriate answer.

echo -e 'HTTP/1.1 204 No content\r\n\r\n' | nc -l -p $port

Note that curl will print just what it receives - nothing. Try curl -v to get a glimpse of what's going on.

2
  • The standard for HTTP is not \n, it's \r\n. Also, The problem is with netcat. Posting a response soon. Sep 2, 2014 at 13:58
  • @moebius_eye reworked my answer after some reading and debugging. The more you know :-) Sep 4, 2014 at 19:50
0

I notice that you are SINGLE quoting the string being sent in your echo statement. Thus, \r and \n are sent literally and not the code for Newline and Return. Try switching the echo to double quotes (").

You can verify this using:

 echo 'whatever\r\n' | od -cb
 echo "better\r\n" | od -cb

Without a line termination, it is likely that the nc program will not transmit the line to the destination.

1
0

Simply,

netcat -l -c "printf 'HTTP/1.1 200 OK\r\n'" -p 8000

printf interprets '\r' and '\n' as escape sequences. echo does not.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .