16

I have a shell script that uses netcat to listen to localhost on port 1111 for web requests. Every time I try accessing localhost:1111/index.html for example I get:

invalid connection to [127.0.0.1] from localhost [127.0.0.1] 60038

the number at the end (60038) seems to be increasing every time I access localhost.

Any suggestions on what's going wrong? And what is the default localhost directory? Where should I put an index.html so that localhost:1111/index.html would work?

EDIT

here is the full script:

#!/bin/sh
while true
do
netcat -vvl localhost -p 1111 -c '
    set -x
    read http_request
    echo HTTP/1.0 200 OK
    echo
    echo "Received HTTP request: $http_request"
'   
done
MinaHany
  • 735
  • 2
  • 6
  • 10
  • The number at the end is the source port, which is randomly chosen; that's the port used by your browser to open the outgoing request. Don't worry about it. Can you post your `netcat` command line? Is the 'invalid connection' message coming from `netcat` or another tool? – mrb Aug 08 '12 at 12:10
  • I just added the full script. I'm not sure if netcat is giving the message, it may be set. I'm not sure what set even does though! – MinaHany Aug 08 '12 at 13:43
  • That script is the listening side. Can you also post the client side? – jw013 Aug 08 '12 at 14:02

1 Answers1

10

Your original script requires that the connection comes from a host named localhost, but for some reason that filtering is failing. Unusual, because it matches exactly the name listed in the error: invalid connection to [127.0.0.1] from localhost [127.0.0.1] 60038

This command will listen on the localhost network interface (and will ignore requests from other interfaces, like your LAN):

netcat -vvl -s localhost -p 1111 -c '
    set -x
    read http_request
    echo HTTP/1.0 200 OK
    echo
    echo "Received HTTP request: $http_request"
'

If you want to listen for requests on all interfaces, you can drop the -s part altogether:

netcat -vvl -p 1111 -c '...'

On my system, if I want to do the same kind of source host filtering without -s, I need to use either 127.0.0.1 or localhost.localdomain:

netcat -vvl localhost.localdomain -p 1111 -c '...'

netcat -vvl 127.0.0.1 -p 1111 -c '...'

In any case, one of the above options should work for you:

$ netcat -vvl 127.0.0.1 -p 1111 -c '
quote>     set -x
quote>     read http_request
quote>     echo HTTP/1.0 200 OK
quote>     echo
quote>     echo "Received HTTP request: $http_request"
quote> '
listening on [any] 1111 ...
connect to [127.0.0.1] from localhost.localdomain [127.0.0.1] 35368
+ read http_request
+ echo HTTP/1.0 200 OK
+ echo
+ echo Received HTTP request: GET / HTTP/1.1
$
mrb
  • 10,048
  • 3
  • 36
  • 36
  • Thanks a lot! changing localhost to 127.0.0.1 seemed to do the trick on firefox. Chrome is handling things differently I guess. – MinaHany Aug 09 '12 at 09:42