The following function is independent of telnet / netcat, since it generates a random port in the local port range and compares it with the list of ports currently used when starting applications.
Should work on any * nix that supports the proc file system. Creates a free ephemeral port that will be used by your application.
function EPHEMERAL_PORT(){ while true; do LISTENING_PORTS=$(cat /proc/net/tcp | awk 'NR >1 {print $2}' | awk -F':' '{print $2}'); LISTENING_PORTS=$(for PORT in ${LISTENING_PORTS}; do echo $((16
Apparently TCP connections can be used as linux file descriptors . The next function uses this technique and should be faster than the previous one.
function EPHYMERAL_PORT(){ LPORT=32768; UPORT=60999; while true; do MPORT=$[$LPORT + ($RANDOM % $UPORT)]; (echo "" >/dev/tcp/127.0.0.1/${MPORT}) >/dev/null 2>&1 if [ $? -ne 0 ]; then echo $MPORT; return 0; fi done }
This is a cross-platform feature that uses osquery to get a list of listening ports. You should also work with Windows.
function EPHYMERAL_PORT(){ while true; do echo "32768 60999" | read LPORT UPORT MPORT=$[$LPORT + ($RANDOM % $UPORT)]; LISTENING_PORTS=$(osqueryi --header=false --list "select port from listening_ports order by port"); if (echo "${LISTENING_PORTS[@]}" | grep -xqv $MPORT); then echo $MPORT; break; fi done }
Instructions for use. Bind the output to a variable and use it in scripts. Tested on Ubuntu 16.04
root@ubuntu :~> EPHYMERAL_PORT 59453 root@ubuntu :~> PORT=$(EPHYMERAL_PORT)
source share