Refactored random public port generation logic