bash-com/pool

66 lines
1.6 KiB
Plaintext
Raw Normal View History

#!/bin/bash
# (1) Init.
#--------------------------------------------------------#
# (1) Get current absolute dir
ROOT=$(dirname `realpath $0`);
# (2) Check argc
test $# -lt 2 && echo -e "error: too fewarguments\n\n\e[1mUSAGE\e[0m\n\tpool <id> <port>\n\n\e[1mARGUMENTS\e[0m\n\t<id>\tThe identifier of the pool (client must match it)\n\t<port>\tTo port to listen to\n" && exit 1;
# (3) Check @PORT range #
MIN_PORT=49152;
MAX_PORT=65535;
test "$2" -gt "$MAX_PORT" -o "$2" -lt "$MIN_PORT" && echo "error: <port> must be between $MIN_PORT and $MAX_PORT" && exit 1;
# (4) Set argument explicit names #
POOL_ID="$1";
POOL_PT="$2";
# (2) Launch pool listener
#--------------------------------------------------------#
# (1) Start the script in background
listfail=0;
# infinite listener
while true; do
# Listen on port @2
echo "(.) listen $POOL_PT";
MSG=`nc -lp $POOL_PT`;
# Do nothing if empty msg
test -z "$MSG" && continue;
# Extract ID - PORT
CLI_ID="`echo -ne \"$MSG\" | sed 's/^\(.\+\):\(.\+\)$/\1/'`";
CLI_PT="`echo -ne \"$MSG\" | sed 's/^\(.\+\):\(.\+\)$/\2/'`";
# if ID does not match
test "$CLI_ID" != "$POOL_ID" && echo " /!\\ wrong id" && continue;
# create new listening socket
echo " [x] creating socket";
# Find an available port
PORT="$MIN_PORT";
while true; do
test "$PORT" = "$POOL_PT" && PORT="`expr $PORT + 1`" && continue;
echo -n " ?? port $PORT -> ";
ss -tl4 "( sport = :$PORT )" | grep "$PORT" >/dev/null 2>&1 || (echo "free"; exit 1) || break;
echo "used";
PORT="`expr $PORT + 1`";
done;
echo " > listen $PORT";
done;