How do I make netcat timeout nonsilently?
I'm trying to send some data to a server with a command like nc -w 3 IP_ADDRESS PORT < data where nc is the netcat from FreeBSD 5.4. When the server doesn't respond within 3 seconds I get no indication of it at all (exit code is 0 and there is no terminal output). How can I send data to the server and be alerted when a timeout occurs?
1 Answer
Use the verbose option and check the output count of bytes sent is non-zero. For example, using awk to exit 1 if the count is zero:
nc -v -w 3 localhost 80 2>/tmp/log
awk '/bytes sent/{exit($2==0)}' < /tmp/log
echo $?