Retrieve port number in a safe manner