diff --git a/qemu/bin/first-free-port b/qemu/bin/first-free-port new file mode 100755 index 0000000..886a367 --- /dev/null +++ b/qemu/bin/first-free-port @@ -0,0 +1,34 @@ +#!/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"