Dave Dave - 5 months ago 32
Bash Question

Finding next open port

Is there any way, using basic Unix commands, to find the next unused port number, starting at port 4444 and going upwards? I'm ssh'ed (via openssh) into a Windows XP machine, running Cygwin tools and using a bash shell.

Thanks, - Dave

Answer

Try this:

for port in $(seq 4444 65000); do echo -ne "\035" | telnet 127.0.0.1 $port > /dev/null 2>&1; [ $? -eq 1 ] && echo "unused $port" && break; done

where

seq 4444 65000 - port range for check
echo -ne "\035" - escape character to force close telnet session (^])

if telnet finishes with exit code 1 that mean connection refused:

$ telnet 127.0.0.1 4444
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
telnet: Unable to connect to remote host
$ echo $?
1

else we decided that connection was success with exit code 0.

EDIT: Special for cygwin: You need to install additional package inetutils that is contain telnet port and use the script as follows:

for port in $(seq 4444 65000); do echo -ne "\035" | /usr/bin/telnet 127.0.0.1 $port > /dev/null 2>&1; [ $? -eq 1 ] && echo "unused $port" && break; done