Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 7 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
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


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.