Use the port 0 trick to find a port not in use.
963007
def _port_not_in_use():
    """"""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    port = 0
    s.bind(('', port))
    _, port = s.getsockname()
    return port
54604
def port(self, check=False):
        
        if not self.__ports:  # refresh ports if sequence is empty
            self.refresh()

        try:
            port = self.__ports.pop()
            if check:
                while not self.__check_port(port):
                    self.release_port(port)
                    port = self.__ports.pop()
        except (IndexError, KeyError):
            raise IndexError("Could not find a free port,\nclosed ports: {closed}".format(closed=self.__closed))
        self.__closed.add(port)
        return port
157616
def return_port(port):
    """"""
    if port in _random_ports:
        _random_ports.remove(port)
    elif port in _owned_ports:
        _owned_ports.remove(port)
        _free_ports.add(port)
    elif port in _free_ports:
        logging.info("Returning a port that was already returned: %s", port)
    else:
        logging.info("Returning a port that wasn't given by portpicker: %s",
                     port)
493195
def getport(self, default=None):
        
        port = self.port
        if port:
            return int(port)
        else:
            return default
388909
def get_free_port(ports=None):
    
    if ports is None:
        with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as _socket:
            _socket.bind(('', 0))
            _, port = _socket.getsockname()
            return port

    # Get ports from the specified list
    for port in ports:
        with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as _socket:
            try:
                _socket.bind(('', port))
                return port
            except socket.error as ex:
                if ex.errno not in (48, 98):
                    raise

    raise RuntimeError("could not find a free port")
985382
def Find(cls, setting_matcher, port_path=None, serial=None, timeout_ms=None):
        """"""
        if port_path:
            device_matcher = cls.PortPathMatcher(port_path)
            usb_info = port_path
        elif serial:
            device_matcher = cls.SerialMatcher(serial)
            usb_info = serial
        else:
            device_matcher = None
            usb_info = 'first'
        return cls.FindFirst(setting_matcher, device_matcher,
                             usb_info=usb_info, timeout_ms=timeout_ms)
787501
def find_available_local_port():
	
	infos = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)
	family, proto, _, _, addr = next(iter(infos))
	sock = socket.socket(family, proto)
	sock.bind(addr)
	addr, port = sock.getsockname()[:2]
	sock.close()
	return port
946138
def dest_ports(self):
        
        start_port = self.blacklist.get('BlacklistEntryDestinationPort')
        if start_port is not None:
            return '{}-{}'.format(
                start_port, self.blacklist.get('BlacklistEntryDestinationPortRange'))
        return 'ANY'
802479
function findPort(cb) {
    var port = tryPort;
    tryPort += 1;

    var server = net.createServer();
    server.listen(port, function(err) {
        server.once('close', function() {
            cb(port);
        });
        server.close();
    });
    server.on('error', function(err) {
        log("port " + tryPort + " is occupied");
        findPort(cb);
    });
}
124613
def delete_port_if_removed(self, port):
        """"""
        instance_type = self.get_instance_type(port)
        if not instance_type:
            return
        port_type = instance_type + a_const.PORT_SUFFIX
        if not db_lib.port_provisioned(port['id']):
            p_res = MechResource(port['id'], port_type, a_const.DELETE)
            self.provision_queue.put(p_res)
1345773
def pick_port(self):
        """"""
        ports = set(range(self.min_port, self.min_port + self.port_range))
        return port_for.select_random(ports)
658697
def check_port(self, port):
        
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind(("localhost", port))
        except socket.error:
            raise UnityWorkerInUseException(self.worker_id)
        finally:
            s.close()
1032362
def is_port_default(self):
        ''''''
        if self.scheme in RELATIVE_SCHEME_DEFAULT_PORTS:
            return RELATIVE_SCHEME_DEFAULT_PORTS[self.scheme] == self.port
615475
def remove_port_callback(self, port, cb):
        """"""
        logger.debug('Removing callback on port [%d] to [%s]', port, cb)
        for port_callback in self.cb:
            if port_callback.port == port and port_callback.callback == cb:
                self.cb.remove(port_callback)
916756
def p_portlist_paren_empty(self, p):
        ''
        p[0] = Portlist(ports=(), lineno=p.lineno(1))
        p.set_lineno(0, p.lineno(1))
557645
def pick_contiguous_unused_ports(
    num_ports,
    retry_interval_secs=3,
    retry_attempts=5):
  """"""
  for _ in range(retry_attempts):
    start_port = portpicker.pick_unused_port()
    if start_port is not None:
      ports = [start_port + p for p in range(num_ports)]
      if all(portpicker.is_port_free(p) for p in ports):
        return ports
      else:
        return_ports(ports)

    time.sleep(retry_interval_secs)

  raise RuntimeError("Unable to obtain %d contiguous unused ports." % num_ports)
917696
def filter_unbound_ports(query):
    """"""
    # hack for pep8 E711: comparison to None should be
    # 'if cond is not None'
    none = None
    port_model = models_v2.Port
    binding_level_model = ml2_models.PortBindingLevel
    query = (query
             .join_if_necessary(port_model)
             .join_if_necessary(binding_level_model)
             .filter(
                 binding_level_model.host != '',
                 port_model.device_id != none,
                 port_model.network_id != none))
    return query