Dave Dave - 2 years ago 106
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 Source

Try this:

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


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 4444
telnet: connect to address Connection refused
telnet: Unable to connect to remote host
$ echo $?

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 $port > /dev/null 2>&1; [ $? -eq 1 ] && echo "unused $port" && break; done
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download