qemush/qemu/bin/first-free-port

35 lines
647 B
Text
Raw Permalink Normal View History

#!/usr/bin/env sh
#set -x
name=$(basename "$0")
used_tcp_ports=$(sed 1d /proc/net/tcp \
| awk '($4 == "0A") { print $2 }' \
| awk -F : '($1 == "00000000" || $1 == "0100007F") { print $2 }' \
| perl -e 'foreach my $line (<>) { print hex($line) . "\n"; }'
)
perror() {
>&2 printf "%s: %s\n" "$name" "$*"
}
port_is_free() {
for used_port in $used_tcp_ports; do
[ "$port" = "$used_port" ] && return 1
done
:
}
port=$1
if ! { [ "$port" -gt 0 ] && [ "$port" -lt 65536 ]; } 2> /dev/null; then
perror "you must specify a valid TCP port"
exit 1
fi
while ! port_is_free; do
port=$((port + 1))
done
printf %s\\n "$port"