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
possible duplicate of How can I check which ports are busy and which ports are free on my Linux machine?
– duDE – 2015-03-04T12:43:24.0531
Why do you need to do that exactly? If you are developing a server, you can bind to port 0 and the OS will allocate a free port for you, you have nothing to search. Otherwise searching and then binding is prone to race conditions. See for example https://stackoverflow.com/questions/1365265/on-localhost-how-do-i-pick-a-free-port-number or https://stackoverflow.com/questions/1075399/how-to-bind-to-any-available-port
– Patrick Mevzek – 2018-02-10T17:57:40.047