From a2d75a7a992ac14a970fc9dc14ee21a71ee95b45 Mon Sep 17 00:00:00 2001 From: Ahurac Date: Wed, 27 Mar 2024 10:41:22 +0100 Subject: [PATCH] =?UTF-8?q?first-free-port=20:=20r=C3=A9=C3=A9criture=20en?= =?UTF-8?q?=20shell?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- qemu/bin/first-free-port | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100755 qemu/bin/first-free-port 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"