10

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.

fdomig
  • 4,417
  • 3
  • 26
  • 39
AJF
  • 1,801
  • 4
  • 27
  • 54
  • AJF : Did you tried it? – NeverGiveUp161 Mar 11 '15 at 15:32
  • @user3560140 Yes. Your command simply shows a list of parameter options and I tried a few. They show TCP ports LISTENING but I believe that is already being used and cannot see a free port. Would the status of a free port be "FREE" or "OPEN" or what? – AJF Mar 11 '15 at 15:39
  • Add -p to that,it will show the process that opened the port: `netstat -antup`,whatever is not in use is FREE :) – NeverGiveUp161 Mar 11 '15 at 15:55
  • @user3560140 Thanks for further feedback. I tried netstat -antup and netstat -lntup and both just provided a list of parameter options as before. So I tried netstat -antp and it stated "Active Connections" and an empty list with the column headings of "Proto", "Local Address", "Foreign Address", "State" and "Off Load State". But as I said it listed no connections – AJF Mar 11 '15 at 17:02

3 Answers3

7

netstat -lntu

This will solve your purpose.

NeverGiveUp161
  • 824
  • 12
  • 33
  • 2
    This command will list open network ports and the processes that own them. Visit : https://superuser.com/a/529831/881022 – JRichardsz Jun 11 '18 at 22:46
7

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"
Fengzmg
  • 710
  • 8
  • 9
4

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

kenorb
  • 155,785
  • 88
  • 678
  • 743