From 309b99ebcfa9d8bcf18c1d3eed1e52787c63f8c7 Mon Sep 17 00:00:00 2001 From: Matthew Treinish Date: Tue, 23 May 2017 15:18:31 -0400 Subject: [PATCH] Add a function to get an available random port This commit adds a new function get_random_port to return a randomly available port from the local port range. Change-Id: Icaed180cc14602a74cdb3fd3456b690d8a4c729c --- functions | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/functions b/functions index 52a82faf0a..4d2703f150 100644 --- a/functions +++ b/functions @@ -732,6 +732,24 @@ function set_systemd_override { sudo systemctl daemon-reload } +# Get a random port from the local port range +# +# This function returns an available port in the local port range. The search +# order is not truly random, but should be considered a random value by the +# user because it depends on the state of your local system. +function get_random_port { + read lower_port upper_port < /proc/sys/net/ipv4/ip_local_port_range + while true; do + for (( port = upper_port ; port >= lower_port ; port-- )); do + sudo lsof -i ":$port" &> /dev/null + if [[ $? > 0 ]] ; then + break 2 + fi + done + done + echo $port +} + # Restore xtrace $_XTRACE_FUNCTIONS