nc Server Not Disconnecting

Below is a very simple web server written with nc(1). The goal is to have a simple script that can stand in for something real when testing configuration. The problem is that nc(1) is not closing the connection.


while true; do
  BODY=$(cat <<EOF
  "Date": "$(date)"
  RESPONSE=$(cat <<EOF
HTTP/1.1 200 OK
Content-Length: $((${#BODY}+1))

echo "$RESPONSE" | nc -l $HOST $PORT

curl(1) will close the connection if the content length is present, but the connection is "left intact".
curl -v
*   Trying
* Connected to ( port 8080 (#0)
> GET / HTTP/1.1
> Host:
> User-Agent: curl/7.47.0
> Accept: */*
< HTTP/1.1 200 OK
< Content-Length: 53
  "Date": "February  6, 2016 at 11:00:55 AM JST"
* Connection #0 to host left intact

If the content length is absent, curl will display a warning and hang after printing the server response.
* no chunk, no close, no size. Assume close to signal end

A timeout can be specified with curl(1), but closing the connection is really the server's responsibility. Also, proprietary clients may not have a timeout option.

The solutions to this problem on the net seem to use -c or -q, presumably for the OSX and Linux versions of nc(1). How can the FreeBSD version of nc(1) be made to close after sending a response?

I realize that HTTP/1.0 assumes closing after the body.
You probably skipped the description of the -N flag while reading the man page... ;)

echo "$RESPONSE" | nc -N -l $HOST $PORT
Thanks. The -N flag resolves some issues.

If a client leaves the socket open and never sends EOF, is there a way to get nc to close the connection after sending a response? Is closing the socket strictly the client's responsibility?