This is an obvious race condition, since other processes on your system might be binding to ports in parallel. So, any solution you find will be imperfect, and you will still need to just write it according to the "try to bind(), if it fails pick a new port number and try again" approach.