Skip to content

Instantly share code, notes, and snippets.

@lusentis
Created January 16, 2014 11:40
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save lusentis/8453523 to your computer and use it in GitHub Desktop.
Save lusentis/8453523 to your computer and use it in GitHub Desktop.
bash script to find a free port to listen to
#!/bin/bash
#
# Please run as root.
# Usage: bash findport.sh 3000 100
#
if [[ -z "$1" || -z "$2" ]]; then
echo "Usage: $0 <base_port> <increment>"
exit 1
fi
BASE=$1
INCREMENT=$2
port=$BASE
isfree=$(netstat -tapln | grep $port)
while [[ -n "$isfree" ]]; do
port=$[port+INCREMENT]
isfree=$(netstat -tapln | grep $port)
done
echo "$port"
exit 0
@Sheraff
Copy link

Sheraff commented Dec 3, 2014

netstat: ln: unknown or uninstrumented protocol I'm getting this. Any clue?

@anboo
Copy link

anboo commented May 28, 2018

while :; do PORT="`shuf -i $LOWERPORT-$UPPERPORT -n 1`"; ss -lpn | grep -q ":$PORT " || break; done

@oakaigh
Copy link

oakaigh commented Dec 10, 2018

read LOWERPORT UPPERPORT < /proc/sys/net/ipv4/ip_local_port_range
while :; do shuffPort="`shuf -i $LOWERPORT-$UPPERPORT -n 1`"; netstat -tapln | grep $shuffPort || break; done

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