More robust way of picking an unused local port

Fixes #584.