I want to see if something is listening on a port on localhost. I was going to use nc and check the exit code.

Something like this:

echo "" | nc localhost 14881
echo $?

Any other suggestions?

link|improve this question

79% accept rate
there are many reasons why you'd want to do this, but I'm curious as to your reason here... it may be possible you can avoid the port-check altogether. Do you have a 'slow start' scenario? where the application daemonizes but takes another minute or two before it actually opens up a listener? or are you just trying to avoid a lengthy timeout situation? or are you unable to handle the case where you get connection refused? – ericslaw Jul 6 '09 at 14:12
feedback

4 Answers

up vote 6 down vote accepted

lsof -i :14881

link|improve this answer
This one provides lots of great data. – msanford Jul 6 '09 at 14:26
On my desktop system this one requires root. – Kyle Brandt Jul 6 '09 at 14:58
feedback

If you are root:

netstat -lnp | grep ':14881 '
link|improve this answer
Just to be clear: it will still work if you aren't root but you won't benefit from seeing the process name bound to it. – Dan Carley Jul 6 '09 at 13:47
feedback

Maybe netstat would be better because the port might not be listening on localhost or it might be blocked by iptables:

netstat -ln  | grep :14881
echo $?

Grep will exit with 1 if there is no match. If you want just tcp and/or udp , add the -u or -t switches to netstat.

link|improve this answer
feedback

netstat -ano | egrep LISTEN | egrep tcp | egrep $PORTNUMBER

link|improve this answer
1  
Woah, lay off the pipes. You can replace the first two egreps with -lt instead of -ao and a normal grep on the port. Or, if you wished, perform everything as a single egrep. – Dan Carley Jul 6 '09 at 13:52
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.