I want to test connectivity to an arbitrary host using netcat. It seems the -w
argument does not actually close the connection after 5 seconds. (This is on Ubuntu 14.04 and netcat-traditional
1.10-40). It will only continue to try connecting for 5 seconds. What I really want to know is if nc
was able to succesfully connect to the host (exit status of 0).
To work around the nc
issue, I've run nc
thorugh the timeout
command. This produces the desired functionality however timeout always exits with a 124 status code.
What I really want is the exit status of nc
. How can I get that when running
timeout 5 nc -w 5 bach; echo $?
From the
timeout
man page (GNU coreutils 8.22) ...So your command would become
However, I've just noticed that the original
nc
command uses the-w
option which isn't what we want here. That tellsnc
to close the connection if it is idle not to give up if the connection takes too long.The option we really want is
-G
which sets the TCP connection timeout. We want-w
as well so that the connection will be closed (because we're not sending anything).This gives a simple
nc
command ofAlternative approach is to just echo an empty line into
nc
to send to the server