handle port conflict

This commit is contained in:
shocknet-justin 2025-09-25 11:29:37 -04:00
parent cc15d1072c
commit 7bf03c3ab7
3 changed files with 61 additions and 12 deletions

32
scripts/ports.sh Normal file
View file

@ -0,0 +1,32 @@
#!/bin/bash
# --- Port Management ---
# Finds an available TCP port, starting from a given base port.
# If the base port is in use, it increments until a free port is found.
#
# @param base_port The starting port number.
# @return The first available port number.
find_available_port() {
local port=$1
while ! is_port_available "$port"; do
log "Port $port is in use. Checking next port..."
port=$((port + 1))
done
echo "$port"
}
# Checks if a given TCP port is available.
#
# @param port The port number to check.
# @return 0 if the port is available, 1 otherwise.
is_port_available() {
local port=$1
if [[ "$OS" == "Mac" ]]; then
# Use lsof on macOS
! lsof -iTCP:"$port" -sTCP:LISTEN -P -t >/dev/null
else
# Use ss on Linux
! ss -lntu | awk '{print $5}' | grep -q ":$port$"
fi
}