Bash snippet to see if something is listening on a port?

7,687

Solution 1

lsof -i :14881

Solution 2

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.

Solution 3

If you are root:

netstat -lnp | grep ':14881 '

Solution 4

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..
Share:
7,687

Related videos on Youtube

Araejay
Author by

Araejay

Updated on September 17, 2022

Comments

  • Araejay
    Araejay over 1 year

    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?

    • Admin
      Admin almost 15 years
      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?
    • Admin
      Admin about 7 years
      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"
  • Dan Carley
    Dan Carley almost 15 years
    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
    Dan Carley almost 15 years
    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.
  • msanford
    msanford almost 15 years
    This one provides lots of great data.
  • Kyle Brandt
    Kyle Brandt almost 15 years
    On my desktop system this one requires root.
  • Justin
    Justin over 7 years
    lsof -i :14881 | grep ":14881" then you can use echo $?