3

I am trying to check port availability and get a return value using shell script. Example: if port 8080 is free then return true, else return false. Can anyone help? I tried with netstat.

jww
  • 97,681
  • 90
  • 411
  • 885
max
  • 613
  • 3
  • 13
  • 26

3 Answers3

18

lsof is your friend:

# lsof -i:8080      # free on my machine
# echo $?
1
# lsof -i:5353      # occupied
COMMAND   PID           USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
mDNSRespo  64 _mdnsresponder    8u  IPv4 0x9853f646e2fecbb7      0t0  UDP *:mdns
mDNSRespo  64 _mdnsresponder    9u  IPv6 0x9853f646e2fec9cf      0t0  UDP *:mdns
# echo $?
0

So in a script, you could use ! to negate the value to test for availability:

if ! lsof -i:8080
then
    echo 8080 is free
else
    echo 8080 is occupied
fi
ajk
  • 1,045
  • 5
  • 9
  • 1
    And one can also redirect the output of `lsof` to `/dev/null` to make it more "scripty". – ivant Nov 11 '15 at 08:29
  • It may also be useful to `grep` for `LISTEN`. Something like `if ! lsof -i:8080 | grep LISTEN > /dev/null`. This may be useful if you have a server running locally as well as an outgoing connection. For example, you're connected to a remote MySQL server while you also have a local MySQL server running. The outgoing connection would be listed with `ESTABLISHED`. These would need to be filtered out if you only want to know if there's a local port being used. – wsams Jul 19 '17 at 23:25
  • Instead of filtering with `grep`, one could use `lsof -i:8080 -sTCP:LISTEN > /dev/null`. – gentooboontoo Sep 18 '19 at 14:14
4

Assuming you are using netstat from net-tools, this is a working example:

function is_port_free { 

    netstat -ntpl | grep [0-9]:${1:-8080} -q ; 

    if [ $? -eq 1 ]
    then 
        echo yes 
    else 
        echo no
    fi
}
  • ${1:-8080} means use first argument as port and 8080 if no first argument
  • grep -q [0-9]:port means match a number followed by a colon followed by port
  • $? is the exit value of the previous command. Zero means all went well. Exit values above 0 indicate an error condition. In the context of grep, exit code 1 means no match. The -q means don't do anything but return the exit value.
  • netstat -ltnp means list numeric ports and IPs for all programs that are listening on a tcp port.
  • a | b means process standard output of a with b

eg.

$ is_port_free 8080
yes

$ is_port_free 22
no
1

How about something simple:

netstat -an|egrep '[0-9]:8080 .+LISTENING'
user590028
  • 11,364
  • 3
  • 40
  • 57