Skip to content

Instantly share code, notes, and snippets.

@jessehub
Created November 17, 2015 18:27
Show Gist options
  • Save jessehub/3ff7448aeaa0303f81a6 to your computer and use it in GitHub Desktop.
Save jessehub/3ff7448aeaa0303f81a6 to your computer and use it in GitHub Desktop.
get next available listening TCP4 port in a range, works with linux netstat and gnu awk
#!/bin/bash
if [[ $# -ne 2 ]]; then
echo "Usage: $0 start end"
exit 1
fi
start=$1
end=$2
# | \ pipes output streaming to the next statement
# ipv4 tcp listening ports and ip's
netstat -ntl -A inet | \
# strip it just down to the ports
awk -F '[ :]+' 'NR<3 {next} {print $5}' | \
# sort ports numerically
sort -n | \
# return the first port in the range that's not currently in use
awk -v port=$start -v end=$end '$0<port {next} $0>end {print "port range exhausted"; exit 1} {if ($0==port) {port+=1}} END {print port}'
@kailuowang
Copy link

Can you do me one more favor? Can you make this thing function and an example on how to use it? Thanks so much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment