title: Binding on a port with netpipes/netcat
body: <p>I am trying to write a simple bash script that is listening on a port and responding with a trivial HTTP response. My specific issue is that I am not sure if the port is available and in case of bind failure I fall back to next port until bind succeeds.</p>
  
  <p>So far to me the easiest way to achieve this was something like:</p>
  
  <pre><code>for (( i=$PORT_BASE; i &lt; $(($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&gt;/dev/null
    if [ $? -eq 0 ] ; then                        #success?
      port=$i
      if [ $DEBUG -eq 1 ] ; then
        echo "bound on port $port"
      fi
      break
    fi
  done
  </code></pre>
  
  <p>Here I am using <code>faucet</code> from <a href="http://www.purplefrog.com/~thoth/netpipes/netpipes.html" rel="nofollow">netpipes</a> Ubuntu package.</p>
  
  <p>The problem with this is that if I simply print "test" to the output, <code>curl</code> complains about non-standard HTTP response (error code 18). That's fair enough as I don't print HTTP-compatible response.</p>
  
  <p>If I replace <code>echo test</code> with <code>echo -ne "HTTP/1.0 200 OK\r\n\r\ntest"</code>, curl still complains:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I think the problem lies in how <code>faucet</code> is printing the response and handling the connection. For example if I do the server side in <code>netcat</code>, curl works fine:</p>
  
  <pre><code>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:$
  </code></pre>
  
  <p>I would be more than happy to replace <code>faucet</code> with <code>netcat</code> in my main script, but the problem is that I want to spawn independent server process to be able to run client from the same base shell. <code>faucet</code> has a very handy <code>--daemon</code> parameter as it forks to background and I can use <code>$?</code> (exit status code) to check if bind succeeded. If I was to use <code>netcat</code> for a similar purpose, I would have to fork it using <code>&amp;</code> and <code>$?</code> would not work.</p>
  
  <p>Does anybody know why <code>faucet</code> isn't responding correctly in this particular case and/or can suggest a solution to this problem. I am not married neither to <code>faucet</code> nor <code>netcat</code> but would like the solution to be implemented using bash or it's utilities (as opposed to write something in yet another scripting language, such as Perl or Python).</p>