How do I determine if a port is in use, e.g. via netstat?

max picture max · Feb 20, 2014 · Viewed 13.5k times · Source

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.

Answer

ajk picture ajk · Feb 20, 2014

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