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?

  • 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
  • with nc correct way will be nc -z "$host" "$port", in bash though the proper way would be echo '123' > /dev/tcp/localhost/port" and if there is nothing listens it will says: "bash: connect: Connection refused" – Danila Ladner Mar 10 '17 at 15:37

lsof -i :14881

  • 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
  • lsof -i :14881 | grep ":14881" then you can use echo $? – Justin Sep 27 '16 at 23:14

If you are root:

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


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

  • 3
    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

sudo ss -lntup will tell you what is listening for TCP/UDP connections - you can filter the output as might be suitable (e.g. listening on, ::1,

If you have python around, you can also create a dumb portscanner (only really worthwhile for TCP, though):

import socket

for p in range(1,2**16):
     s = socket.create_connection(('',p))
     print "Listener on tcp/{}".format(p)

I use this in bash for exiting when no-one listening to this port.

if [[ $(netstat -ltn | grep ":${port} " | wc -l) -eq "0" ]] ; then echo "Port $port not listened to" && exit 1; fi
  • Using bash double brackets and comparing against wc for easy reading..
  • Passing the "-c" argument to grep obviates the need for "wc -l" – parkamark Mar 10 '17 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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