getting the next available tcp port (freebsd only)

in doing some automated sysadmin tasks like ssh port forwarding you may need to dig at runtime for a free tcp port to use



#!/bin/sh
nextport=1025
while [ $nextport -lt 65534 ] ; do
 
 count=$((`sockstat -4 -lc -P tcp -p $nextport|wc -l`-1))
 if [ $count -eq 0 ] ; then
  echo $nextport;
  exit 0;
 fi
 nextport=$(($nextport+1))
done
echo 0
exit 1

No comments:

Post a Comment