Fixes random port testing problem

Fixes random port testing problem (#685).
Not entirely sure about this loop. Maybe just keep it as it was in obtain_port.