#!/bin/sh
# portfind -- find what is using a port, or find a free port
# Usage: portfind <port> -- show what's on this port
# portfind --free -- find a random free port
# portfind --free 8000 -- find free port starting from 8000
# Update: need to expand to include a port mapping of --free jumps to first before suggesting random free port.
if [ "$1" = "--free" ]; then
start="${2:-3000}"
port="$start"
while ss -tlnp "sport = :$port" 2>/dev/null | grep -q LISTEN; do
port=$((port + 1))
done
echo "$port"
else
port="$1"
[ -z "$port" ] && { echo "Usage: portfind <port> | portfind --free [start]"; exit 1; }
echo "=== TCP ==="
ss -tlnp "sport = :$port" 2>/dev/null
echo "=== UDP ==="
ss -ulnp "sport = :$port" 2>/dev/null
fi