Yes! By default, netcat (or nc) does not explicitly notify you when the remote peer closes the connection. However, you can use some workarounds to detect this event:
1. Using nc with -v (Verbose Mode)
Some versions of netcat (like ncat from Nmap or netcat-openbsd) support verbose mode, which may show connection termination:
sh
nc -v <host> <port>
If the remote peer closes the connection, you might see a message like:
code
Connection to <host> <port> port [tcp/<service>] succeeded!
followed by no further output.
2. Using socat Instead of netcat
socat is a more powerful alternative that can explicitly detect connection closure:
sh
socat - TCP:<host>:<port>
When the remote peer closes the connection, socat will exit, and you can check its exit status.
3. Using strace to Monitor netcat
You can trace system calls to detect when the connection is closed:
sh
strace -e trace=read,write nc <host> <port>
When the remote peer closes the connection, you'll see a read returning 0 (EOF).
4. Using a Wrapper Script
You can write a simple script to detect when netcat exits due to a closed connection:
sh
#!/bin/bash
nc <host> <port> | while read -r line; do
echo "$line"
done
echo "Remote peer closed the connection."
This will print a message when the remote side closes the connection.
5. Using timeout to Detect Inactivity
If the remote peer closes the connection, netcat will exit, and you can detect this: