# nc Server Not Disconnecting



## sgeos (Feb 6, 2016)

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.

```
#/bin/sh

HOST=127.0.0.1
PORT=8080

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

${BODY}
EOF
)
echo "$RESPONSE" | nc -l $HOST $PORT
done
```

curl(1) will close the connection if the content length is present, but the connection is "left intact".

```
curl -v http://127.0.0.1:8080/
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 8080 (#0)
> GET / HTTP/1.1
> Host: 127.0.0.1:8080
> 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 127.0.0.1 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.


----------



## worldi (Feb 6, 2016)

You probably skipped the description of the -N flag while reading the man page... 


```
...
echo "$RESPONSE" | nc -N -l $HOST $PORT
...
```


----------



## sgeos (Feb 6, 2016)

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?


----------



## Juha Nurmela (Feb 6, 2016)

```
Connection: close
```
 header is not a solution, but related.

Juha


----------

