@@ -53,19 +53,55 @@ elif [ "${AM_BWRAPPED-}" != "yes" ]; then
5353fi
5454
5555# need a unique port since may run the same time as testsuite
56+ # Track ports already assigned in this script run to prevent intra-run collisions
57+ used_ports=()
58+
5659generate_port () {
5760 # -------------------------------------------------------------------------#
58- # Generate a random port number
61+ # Generate a random port number, guaranteed unique within this script run.
62+ # Checks both the intra-run used_ports list and system-level bound ports.
5963 # -------------------------------------------------------------------------#
64+ local attempts=0 collision p
6065
61- if [[ " $OSTYPE " == " linux" * ]]; then
62- port=$(( $(od - An - N2 / dev/ urandom) % (65535 - 49512 ) + 49512 ))
63- elif [[ " $OSTYPE " == " darwin" * ]]; then
64- port=$(( $(od - An - N2 / dev/ random) % (65535 - 49512 ) + 49512 ))
65- else
66- echo " skipping due to unsupported OS"
67- exit 0
68- fi
66+ while true ; do
67+ if [[ " $OSTYPE " == " linux" * ]]; then
68+ p=$(( $(od - An - N2 / dev/ urandom) % (65535 - 49512 ) + 49512 ))
69+ elif [[ " $OSTYPE " == " darwin" * ]]; then
70+ p=$(( $(od - An - N2 / dev/ random) % (65535 - 49512 ) + 49512 ))
71+ else
72+ echo " skipping due to unsupported OS"
73+ exit 0
74+ fi
75+
76+ # Check against ports already assigned in this run
77+ collision=0
78+ for up in " ${used_ports[@]} " ; do
79+ if [ " $up " = " $p " ]; then
80+ collision=1
81+ break
82+ fi
83+ done
84+
85+ # Also check if the port is already bound on this system
86+ if [ $collision -eq 0 ]; then
87+ if command -v ss & > /dev/null; then
88+ ss -lnt 2> /dev/null | grep -q " :${p} [[:space:]]" && collision=1
89+ elif command -v netstat & > /dev/null; then
90+ netstat -lnt 2> /dev/null | grep -q " :${p} [[:space:]]" && collision=1
91+ fi
92+ fi
93+
94+ [ $collision -eq 0 ] && break
95+
96+ (( attempts++ ))
97+ if [ $attempts -ge 100 ]; then
98+ echo " ERROR: generate_port could not find a free port after 100 attempts"
99+ exit 1
100+ fi
101+ done
102+
103+ port=$p
104+ used_ports+=(" $p " )
69105}
70106
71107WOLFSSL_SERVER=./examples/server/server
0 commit comments