Linux command get unused port

I'm looking for a command or script which returns an unused port on my ubuntu linux system. I have look on internet and the only thing I find is about the used/Listen port with the nestat command. Apparently something with the netstat command will work but don't know what exactly. Any idea how?

Thanks.


Solution 1:

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

Solution 2:

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?