Search code examples
bashnetcat

Issue with netcat timeout


Why does the following netcat command not time out if the attempt to connect takes longer than 3 seconds (ie: when the port isn't open)? I assumed that the -w flag would be what I needed. OS is OSX 10.9.

nc -v -z -w 3 127.0.0.1 5050

Assuming that worked, I planned to implement like this (unsure if this will work, total bash noob)

nc -v -z -w 3 127.0.0.1 5050 | /dev/null && echo "Online" || echo "Offline"


Solution

  • You need to redirect to /dev/null, not pipe to it. Try the following:

    nc -v -z -w 3 127.0.0.1 5050 &> /dev/null && echo "Online" || echo "Offline"
    

    On my machine, port 5050 isn't open, and I get the following:

    $ nc -v -z -w 3 localhost 5050 &> /dev/null && echo "Online" || echo "Offline"
    Offline