From 26084f1608ea037bb524fe0e60bd06098fd812d2 Mon Sep 17 00:00:00 2001 From: EuAndreh Date: Wed, 29 Mar 2023 09:19:30 -0300 Subject: bin/free-port: Try random ports over sequential ones To diminish race-conditions where two separate processes call free-port(1) and get the same port that is free at that time, but only one is able to bind to it. --- bin/free-port | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'bin') diff --git a/bin/free-port b/bin/free-port index 2476b4b..1c2af61 100755 --- a/bin/free-port +++ b/bin/free-port @@ -61,13 +61,18 @@ done shift $((OPTIND - 1)) -PORT=1024 +MIN_PORT=1024 +MAX_PORT=65536 + +gen_port() { + shuf -n1 -i "${MIN_PORT}-${MAX_PORT}" +} while true; do + PORT="$(gen_port)" if ! lsof -s TCP:LISTEN -i ":$PORT" >/dev/null; then break fi - PORT=$((PORT + 1)) done echo "$PORT" -- cgit v1.2.3