Sunday, 27 August 2017

How to generate random port number

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"

No comments:

Post a Comment

Thank You for your valuable comment

Difference between class level and object locking and static object lock

1) Class level locking will lock entire class, so no other thread can access any of other synchronized blocks. 2) Object locking will lo...