Get available port from specified range I have a situation where we need to be able to run multiple instances of a Spring app with dynamically assigned ports defined at runtime. I need to be able to get an available port at runtime, create some associated file structure for dedicated logs &amp;c, and plug the port number into the command-line arguments passed to Java.

Below is an adaptation of some code I pulled off the Unix exchange and tweaked. It currently seems to do what I need - runs in single-digit milliseconds, accepts upper an lower bounds or provides reasonable defaults, won't spin off into an infinite loop if someone does something stupid like specifying the same upper and lower bound as a port that's already in use, doesn't actually send a newline into a port that's already in use, etc.

Anyone see a flaw, or a way to make it cleaner?

I know there's a possible race condition, and suggestions for that are welcome. I don't need non-bash portability. 

getPort() {
    local -i lo=${1:-50000} hi=${2:-65000}
    local -i range=$(( hi - lo + 1 )) candidate
    for try in {1..999}
    do  candidate=$(( lo + ( $RANDOM$RANDOM % range ) ))
        { printf "" &gt;/dev/tcp/127.0.0.1/$candidate ||
          printf "" &gt;/dev/tcp/-thisIP,redacted-/$candidate
        } &gt;/dev/null 2&gt;&amp;1 || { echo $candidate; return 0; }
    done
    return 1;
}


ADDENDUM



Since I am only interested in ports on the local machine, I should be ok if I test both localhost and every IP for this machine, which in my case will be only one. (IP redacted above.)

Yes?

Also, since someone could pass in 0 and 65000 as args, just using a 16bit $RANDOM alone doesn't cover all cases. I took the cheesy-easy route and used $RNADOM$RANDOM, which has some weirdness since about 2/3 of the time the 5th digit from the right will only be one of [123], and the distribution curve will slope up from the low end, but these aren't problematic in my case. Still, I'd love to see examples of how to smooth it out.
There's an obvious flaw if the candidate port is closed on 127.0.0.1 but open on a different interface that you want your service to bind to.  That's particularly relevant if you want it to listen on all interfaces (0.0.0.0).

If your service binds to the localhost address, then that's obviously not a concern.