Linux command get unused port
netstat -lat
gives the complete list of listening and established ports.
When a port is not on any of those states doesn't exist for the system, so you won't find a command that shows the list of unused ports.
Keep in mind that there are 65535 ports, so anything that isn't on netstat -lat
is an unused port.
The following bash script will do a simple scan of tcp ports, and let you know which are open and which are closed :
#!/bin/bash
IP=$1
first_port=$2
last_port=$3
function scanner
{
for ((port=$first_port; port<=$last_port; port++))
do
(echo >/dev/tcp/$IP/$port)> /dev/null 2>&1 && echo $port open || echo "$port closed"
done
}
scanner
If you save it as portscan.sh then it must be run as ./portscan.sh IP first_port last_port, for example: ./portscan 127.0.0.1 20 135
will scan the local equipment from ports 20 to 135
Ruby 2.x (one-liner):
ruby -e 'require "socket"; puts Addrinfo.tcp("", 0).bind {|s| s.local_address.ip_port }'
On my machine right now that printed:
42644
A subsequent invocation printed:
36168
This technique causes the current user to request an unused port (bind to port "0"), and then prints out the port number that the operating system provided. And since the current user is the one asking, ports below 1024 will not be returned (unless current user = root).
Credit where credit's due - this solution comes from a comment by Franklin Yu on unix.stackexchange.com's What's the easiest way to find an unused local port?
Short bash script that randomly generates a number between 1025 and 60000 and loops until that number isn't found in the list of used ports. This is a quick 'n dirty solution that has a bias to larger ports:
CHECK="do while"
while [[ ! -z $CHECK ]]; do
PORT=$(( ( RANDOM % 60000 ) + 1025 ))
CHECK=$(sudo netstat -ap | grep $PORT)
done
echo $PORT