Below is the code to generate the random port number based on the port range configuration in machine level . It will generate a port by calculating ranges define and check if this port is being used in that machine. If port is not in use then it will return that number. This is useful for creating docker containers where you want to generate some random port to expose.
#!/bin/ksh
read LOWERPORT UPPERPORT < /proc/sys/net/ipv4/ip_local_port_range
while :
do
PORT="`shuf -i $LOWERPORT-$UPPERPORT -n 1`"
ss -lpn | grep -q ":$PORT " || break
done
echo "Your port is : $PORT"
#!/bin/ksh
read LOWERPORT UPPERPORT < /proc/sys/net/ipv4/ip_local_port_range
while :
do
PORT="`shuf -i $LOWERPORT-$UPPERPORT -n 1`"
ss -lpn | grep -q ":$PORT " || break
done
echo "Your port is : $PORT"