def get_random_port(socket_type='all', min_port=5000, max_port=60000):
 assert (socket_type in ('all', 'tcp', 'udp')), ('Invalid socket type %s' % type(socket_type))
 assert isinstance(min_port, int), ('Invalid min_port type %s' % type(min_port))
 assert isinstance(max_port, int), ('Invalid max_port type %s' % type(max_port))
 assert (0 < min_port <= max_port <= 65535), ('Invalid min_port and mac_port values %s, %s' % (min_port, max_port))
 working_port = None
 try_port = random.randint(min_port, max_port)
 while (try_port <= 65535):
  if check_random_port(try_port, socket_type):
   working_port = try_port
   break
  try_port += 1
 logger.debug('Got a working random port %s', working_port)
 return working_port

def get_random_port ( socket_type = 'all' , min_port = 5000 , max_port = 60000 ) : assert ( socket_type in ( 'all' , 'tcp' , 'udp' ) ) , ( 'Invalid socket type %s' % type ( socket_type ) ) assert isinstance ( min_port , int ) , ( 'Invalid min_port type %s' % type ( min_port ) ) assert isinstance ( max_port , int ) , ( 'Invalid max_port type %s' % type ( max_port ) ) assert ( 0 < min_port <= max_port <= 65535 ) , ( 'Invalid min_port and mac_port values %s, %s' % ( min_port , max_port ) ) working_port = None try_port = random . randint ( min_port , max_port ) while ( try_port <= 65535 ) : if check_random_port ( try_port , socket_type ) : working_port = try_port break try_port += 1 logger . debug ( 'Got a working random port %s' , working_port ) return working_port
gets a random port number that works .