Bash Snippet to Dynamically Find Free Ports

Useful snippet I wrote for Docker container creation and dynamic port assignment.

ALLOCATED_PORT_LIST=()

function getFreePort()
{
	CHECK="do while"

	while [[ ! -z $CHECK ]]; do
		PORT=$(( ( RANDOM % 60000 )  + 1025 ))
		CHECK=$(sudo netstat -ap | grep $PORT)
	done

	echo $PORT
}

function getFreePort_Unallocated()
{
	PORT=$(getFreePort)
	
	MATCH_FOUND="false"

	for ALLOCATED_PORT in "${ALLOCATED_PORT_LIST[@]}"
	do
		if [ $PORT == $ALLOCATED_PORT ]; then
			MATCH_FOUND="true"
		fi
	done
	
	if [ $MATCH_FOUND == "true" ]; then
		getFreePort_Unallocated
	else
        ALLOCATED_PORT_LIST+=("$PORT")
		echo $PORT
	fi
}

PORT1=$(getFreePort_Unallocated)
PORT2=$(getFreePort_Unallocated)
PORT3=$(getFreePort_Unallocated)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s