Port binding with netpipes / netcat

I am trying to write a simple bash script that listens on a port and responds with a trivial HTTP response. My particular problem is that I am not sure if the port is available and if the binding fails, I return to the next port until the binding is complete.

So far, for me the easiest way to achieve this has been:

for (( i=$PORT_BASE; i < $(($PORT_BASE+$PORT_RANGE)); i++ ))
do
  if [ $DEBUG -eq 1 ] ; then
    echo trying to bind on $i
  fi
  /usr/bin/faucet $i --out --daemon echo test 2>/dev/null
  if [ $? -eq 0 ] ; then                        #success?
    port=$i
    if [ $DEBUG -eq 1 ] ; then
      echo "bound on port $port"
    fi
    break
  fi
done

Here I use faucetfrom the netpipes package Ubuntu.

The problem is that if I just print a โ€œtestโ€ on the output, it curlcomplains about a non-standard HTTP response (error code 18). This is fair enough since I am not printing an HTTP compatible response.

If I replaced echo testwith echo -ne "HTTP/1.0 200 OK\r\n\r\ntest", curl still complains:

user@server:$ faucet 10020 --out --daemon echo -ne "HTTP/1.0 200 OK\r\n\r\ntest"
...
user@client:$ curl ip.of.the.server:10020
curl: (56) Failure when receiving data from the peer

, , faucet . , netcat, curl :

user@server:$ echo -ne "HTTP/1.0 200 OK\r\n\r\ntest\r\n" | nc -l 10020
...
user@client:$ curl ip.of.the.server:10020
test
user@client:$

faucet netcat script, , , . faucet --daemon, , $? ( ), , bind. netcat , & $? .

- , faucet / . faucet, netcat, , bash ( , - , Perl Python).

+3
4
faucet 10020 --out --daemon \
    echo -ne "HTTP/1.0 200 OK\r\nContent-Length: 4\r\n\r\ntest"

. , echo , shutdown , close, curl -1 ( ), 0 ( shutdown) recvfrom.

socat, , .

socat tcp-l:10020,fork,reuseaddr \
    exec:'echo -ne "HTTP/1.0 200 OK\r\n\r\ntest"'
+4

, "" . :

-F    fork after connection accepted   (TCP concurrent server)

http://www.icir.org/christian/sock.html

Bash, :

echo $'HTTP/1.0 200 OK\r\n\r\ntest\r\n'
+2

Do you really need to use the HTTP protocol, or is it just to please the curl? if he is the last, just connect

 faucet $port --out --daemon echo test

with

 hose $server $port --in cat
+1
source

How about using tcpserver from the DJB ucspi-tcp package.

http://lserinol.blogspot.com/2008/12/simple-tcp-server-with-djb-tcpserver.html

An additional alternative to netcat or nc is ncat (part of nmap).

+1
source

Source: https://habr.com/ru/post/1784258/


All Articles