Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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?

share|improve this question
    
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

4 Answers 4

up vote 6 down vote accepted

lsof -i :14881

share|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

If you are root:

netstat -lnp | grep ':14881 '
share|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

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.

share|improve this answer

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

share|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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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