4

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?

Amandasaurus
  • 30,211
  • 62
  • 184
  • 246
  • 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 06 '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

6 Answers6

9

lsof -i :14881

lexsys
  • 2,863
  • 5
  • 30
  • 34
4

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.

Kyle Brandt
  • 82,107
  • 71
  • 302
  • 444
2

If you are root:

netstat -lnp | grep ':14881 '
Dan Carley
  • 25,189
  • 5
  • 52
  • 70
  • 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 06 '09 at 13:47
1

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

$port="14881"
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..
Bob
  • 5
  • 1
Bob
  • 11
  • 1
0

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

flybywire
  • 587
  • 4
  • 9
  • 20
  • 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 06 '09 at 13:52
0

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 127.0.0.1, ::1, 0.0.0.0).

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):
   try:
     s = socket.create_connection(('127.0.0.1',p))
     print "Listener on tcp/{}".format(p)
   except:
     continue
iwaseatenbyagrue
  • 3,588
  • 12
  • 22