@@ -29,11 +29,13 @@ SKIP_EXAMPLES=0
2929# --- Helpers ---
3030
3131# Wait for a TCP port to be listening
32- # Uses ss to check without connecting (nc -z would consume the accept slot)
32+ # Uses ss/netstat to check without connecting (nc -z would consume the accept slot)
3333wait_for_port () {
3434 local port=" $1 " timeout=" ${2:- 500} " elapsed=0
3535 while [ $elapsed -lt $timeout ]; do
36- if ss -tln 2> /dev/null | grep -q " :${port} " ; then
36+ if command -v ss > /dev/null 2>&1 ; then
37+ ss -tln 2> /dev/null | grep -q " :${port} " && return 0
38+ elif netstat -tln 2> /dev/null | grep -q " :${port} " ; then
3739 return 0
3840 fi
3941 sleep 0.01
@@ -42,6 +44,21 @@ wait_for_port() {
4244 return 1
4345}
4446
47+ # Check if a port is in use (returns 0 if port is in use)
48+ check_port_in_use () {
49+ local port=" $1 "
50+ if command -v nc > /dev/null 2>&1 ; then
51+ nc -z localhost " $port " 2> /dev/null
52+ return $?
53+ elif command -v ss > /dev/null 2>&1 ; then
54+ ss -tln 2> /dev/null | grep -q " :${port} "
55+ return $?
56+ elif netstat -tln 2> /dev/null | grep -q " :${port} " ; then
57+ return 0
58+ fi
59+ return 1 # no tool available, assume in use to be safe
60+ }
61+
4562# Pick an available random port (returns port on stdout)
4663pick_available_port () {
4764 local port attempts=0
@@ -51,7 +68,7 @@ pick_available_port() {
5168 else
5269 port=$(( (RANDOM % 55000 ) + 10000 ))
5370 fi
54- if ! nc -z localhost " $port " 2> /dev/null ; then
71+ if ! check_port_in_use " $port " ; then
5572 echo " $port "
5673 return 0
5774 fi
@@ -240,7 +257,7 @@ if [ $IS_FWTPM_MODE -eq 1 ]; then
240257 # --- fwTPM mode: we manage the server lifecycle ---
241258
242259 # Check if a server is already running (e.g. started by CI)
243- if [ $IS_SWTPM_MODE -eq 1 ] && ss -tln 2> /dev/null | grep -q " : ${ FWTPM_PORT} " ; then
260+ if [ $IS_SWTPM_MODE -eq 1 ] && check_port_in_use " $ FWTPM_PORT" ; then
244261 echo " Server already running on port $FWTPM_PORT "
245262 if [ $HAS_GETENV -eq 1 ]; then
246263 export TPM2_SWTPM_PORT=" $FWTPM_PORT "
312329 export TPM2_SWTPM_PORT=" $FWTPM_PORT "
313330 fi
314331
315- if ! ss -tln 2> /dev/null | grep -q " : ${ FWTPM_PORT} " ; then
332+ if ! check_port_in_use " $ FWTPM_PORT" ; then
316333 echo " No TPM server on port $FWTPM_PORT , skipping (start one with: tpm_server &)"
317334 exit 77
318335 fi
0 commit comments