Created
November 17, 2015 18:27
-
-
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
This file contains 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
#!/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}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you do me one more favor? Can you make this thing function and an example on how to use it? Thanks so much.