From 2ffc0e38f4873037f10f5f1408578fd4e6d645f0 Mon Sep 17 00:00:00 2001 From: "xiongdian.me" Date: Tue, 8 Aug 2023 18:05:14 +0800 Subject: [PATCH] common.sh: is_port_free and get_free_port --- tools/common.sh | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tools/common.sh b/tools/common.sh index 0023c82..ddae15f 100755 --- a/tools/common.sh +++ b/tools/common.sh @@ -233,6 +233,31 @@ get_os_name() echo $ans } +is_port_free() { + ( echo $1 | grep -qxE "[1-9][0-9]{0,4}" ) || false + local cmd + case $(get_os_type) in + macos ) cmd="netstat -van | grep -q \".$1\"" ;; + cygwin|msys ) cmd="netstat -ano | grep -q \":$1\"" ;; + *) cmd="netstat -tuanp | grep -q \":$1\"" ;; + esac + if eval $cmd; then + return 2 + else + return 0 + fi +} + +get_free_port() { + while + local port=$(shuf -n 1 -i 49152-65535) + ! is_port_free $port + do + continue + done + echo $port +} + # if bash-ed, else source-d if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then $1 "${@:2}"