Created
April 4, 2019 15:11
-
-
Save elasticdog/6f5c0ee4064da162f4efc48d3934a838 to your computer and use it in GitHub Desktop.
A pure Bash script to return a random *unused* ephemeral TCP port
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# ephemeral-port | |
# | |
# A script that returns a random *unused* TCP port within the IANA-suggested | |
# ephemeral port range of 49152 to 65535. Defaults to checking the localhost, | |
# but takes an optional hostname as an argument. | |
# | |
# See: | |
# - https://en.wikipedia.org/wiki/Ephemeral_port | |
# - http://mywiki.wooledge.org/BashFAQ/026 | |
# - http://tldp.org/LDP/abs/html/devref1.html#DEVTCP | |
# | |
readonly HOST=${1:-127.0.0.1} | |
readonly FLOOR=49152 | |
readonly RANGE=$((65535 - FLOOR + 1)) | |
# Returns random number from 0 to ($1-1) in global var 'r'. | |
rand() { | |
local max=$((32768 / $1 * $1)) | |
while (((r = RANDOM) >= max)); do :; done | |
r=$((r % $1)) | |
} | |
# Check if TCP connections to $HOST on port $1 are refused. | |
connection_refused() { | |
! (echo "" >"/dev/tcp/${HOST}/${1}") &>/dev/null | |
} | |
while true; do | |
rand $RANGE | |
candidate=$((FLOOR + r)) | |
if connection_refused $candidate; then | |
echo $candidate | |
break | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment