Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with netcat timeout

Tags:

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"

like image 364
anditpainsme Avatar asked Jun 13 '14 05:06

anditpainsme


People also ask

What is verbose in Netcat?

In netcat, Verbose is a mode which can be initiated using [-v] parameter. Now verbose mode generates extended information. Basically, we will connect to a server using netcat two times to see the difference between normal and verbose mode.

Does Netcat use TCP or UDP?

By default Netcat uses the TCP protocol for its communications, but it can also UDP using the -u option. As we mentioned at the previous step, Netcat lets you convert your PC in a server. In this case we're going to establish the connection between the server and the client but using UDP.

What is the E flag on Netcat?

Remote Administration with netcat Netcat-traditional comes with '-e' option which can be used to bind a program (i.e cmd.exe in Windows or bash in Linux) with a port, that means netcat will act as communicator between the program and the remote PC.

How do I exit Netcat?

Ctrl+d is the correct way to close netcat in the *Nix world.


2 Answers

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
like image 103
CDahn Avatar answered Sep 21 '22 12:09

CDahn


Since Mac OS X 10.8.x, nc has used the -G option to set the timeout for initiating a connection. This is separate from the -w option, which sets the timeout for a connection that has been made but has gone idle.

If you are trying to use nc for port scanning, i.e. nc -v -z 10.0.1.1 1-1023, it will spend over a minute trying to connect to each non-responding port unless you add a -G timeout value:

nc -v -z -G 1 10.0.1.1 1-1023

That's one second per port scanned — much more useful.

like image 29
MacTroy Avatar answered Sep 25 '22 12:09

MacTroy