How to find a free TCP port

20,721

Solution 1

netstat -lntu

This will solve your purpose.

Solution 2

Inspired by https://gist.github.com/lusentis/8453523

Start with a seed port, and increment it till it is usable

BASE_PORT=16998
INCREMENT=1

port=$BASE_PORT
isfree=$(netstat -taln | grep $port)

while [[ -n "$isfree" ]]; do
    port=$[port+INCREMENT]
    isfree=$(netstat -taln | grep $port)
done

echo "Usable Port: $port"

Solution 3

In Bash you can write simple for loop to check which TCP ports are free, e.g.

$ for i in {1..1024}; do (exec 2>&-; echo > /dev/tcp/localhost/$i && echo $i is open); done
22 is open
25 is open
111 is open
587 is open
631 is open
841 is open
847 is open
1017 is open
1021 is open

For more info, check: Advanced Bash-Scripting Guide: Chapter 29. /dev and /proc

Share:
20,721
AJF
Author by

AJF

Updated on July 09, 2022

Comments

  • AJF
    AJF almost 2 years

    How do I find a completely free TCP port on a server? I have tried the command line;

    netstat -an
    

    but I am told the ones with a status of LISTENING are already being used.

    I also tried a tool called TCPView but again it only showed which TCP ports were being used. I know how to telnet to a port to check its open but I need to find one that is free.

  • JRichardsz
    JRichardsz almost 6 years
    This command will list open network ports and the processes that own them. Visit : superuser.com/a/529831/881022
  • stevec
    stevec almost 4 years
    Should this work on mac? It completed without returning any output for me