Q:

How to get Netcat to return unused ports

I tried this command to try to find unused ports. What I want it to do is run netcat on a range of ports, find the ones that are not running services, grep the first one of those lines of output, and then use sed to output the port number only.
nc -z <my url> 5000-5010 | grep -m 1 succeeded | sed 's/[^0-9]//g'

But when I try and launch a service using the port that is returned, I get a message saying the port is currently in use.
I found out netcat success means a service is running on the port, but when I try this instead
nc -zv <my url> 5000-5010 | grep -m 1 failed | sed 's/[^0-9]//g'

I get nothing, even though most lines of output contain the word failed.
Going through the man pages revealed that netcat -z only returns output for successful results, though why line after line of failed connection appears on my terminal window is still beyond me.
How can I use netcat to view the first port a connection failed on?

A:

The nc -v command writes the failed/succeeded messages on standard error, not the standard output. You can redirect stderr to stdout using 2>&1.
nc -zv <my url> 5000-5010 2>&1 | grep -m 1 failed

to get the failed line.
See http://www.cyberciti.biz/faq/redirecting-stderr-to-stdout/
By the way, I suggest you use awk to get the port number from the output line:
nc -zv <my url> 5000-5010 2>&1 | grep -m 1 failed | awk '{print $6}'

which prints the value in the 6th column of the output line.

