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

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


lsof is your friend:

# lsof -i:8080      # free on my machine# echo $?1# lsof -i:5353      # occupiedCOMMAND   PID           USER   FD   TYPE             DEVICE SIZE/OFF NODE NAMEmDNSRespo  64 _mdnsresponder    8u  IPv4 0x9853f646e2fecbb7      0t0  UDP *:mdnsmDNSRespo  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:8080then    echo 8080 is freeelse    echo 8080 is occupiedfi


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 8080yes$ is_port_free 22no


How about something simple:

netstat -an|egrep '[0-9]:8080 .+LISTENING'