I think you'll end up with a race-condition if you try to look at all open ports and then pick one. Instead, why not start at a fixed base and work your way up till you find an open one? Just keep $port++ till you find one that's free.
-sam
Comment on Re: What's the best way to find an unused TCP port on the local system
Yeah, I'm willing to live with a small race condition here. This is an internal tool and the frequency with which the tool is used means that the frequency at which two servers would run at the same time is very low, and thus the probability of the race condition become a concern is extremely low indeed.
Since this server is actually a c++ app and I have to communicate the port number by writing a new configuration file each time I don't want to muck with catching a failed startup, determine if it's because the port was in use, write a new config file and try again.
--DrWhy
"If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."