Search code examples
node.jssocketstcpnetcat

netcat doesn't send final FIN to close the connection


I am playing with self-made nodejs tcp server and testing its behaviour with netcat under Linux. Upon the establishing the connection the server sends 'Test' string down the line and closes the socket. I expect the netcat to close the connection on its side by sending appropriate tcp packets, but it doesn't! Here is what I do:

nc -v localhost 9000

After that the whole conversation looks like this:

netcat --> server (SYN)
netcat <-- server (SYN, ACK)
netcat --> server (ACK)
netcat <-- server (PSH, ACK)
netcat --> server (ACK)
netcat <-- server (FIN, ACK)
netcat --> server (ACK)

At this point I would expect netcat to send FIN but it never does. Connection hangs in FIN-WAIT-2 on one side and CLOSE-WAIT on the other.

If I try the same thing with telnet:

telnet localhost 9000

it behaves as expected and terminates the connection after receiving 'Test' string.

The question is why does netcat behaves differently?


Solution

  • netcat was designed to work until both sides have closed the connection. You still have one side left open.

    When the server closes the connection with FIN the connection remains in a half-open state where you can send data and the server can receive it. The connection will remain in this state until you close netcat's stdin (type Ctrl-D), which makes it send a FIN packet to the server.