Try to bind a port. Default=0 selects a free port.
326604
def pick_free_port(hostname=REDIRECT_HOST, port=0):
    
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.bind((hostname, port))  # port=0 finds an open port
    except OSError as e:
        log.warning("Could not bind to %s:%s %s", hostname, port, e)
        if port == 0:
            print('Unable to find an open port for authentication.')
            raise AuthenticationException(e)
        else:
            return pick_free_port(hostname, 0)
    addr, port = s.getsockname()
    s.close()
    return port
896422
def find_free_port():
    """"""
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        sock.bind(('', 0))
        return sock.getsockname()[1]
1044883
def Tethering_unbind(self, port):
		
		assert isinstance(port, (int,)
		    ), "Argument 'port' must be of type '['int']'. Received type: '%s'" % type(
		    port)
		subdom_funcs = self.synchronous_command('Tethering.unbind', port=port)
		return subdom_funcs
736695
public void setPort(int port)
    {
        if (_address == null || _address.getHostName() == null)
            _address= new InetSocketAddress(port);
        else
            _address= new InetSocketAddress(_address.getHostName(), port);
    }
932302
def port(self):
        
        return self._val.port or DEFAULT_PORTS.get(self._val.scheme)
477542
def create_port_binding(self, port, host):
        """"""
        if not self.get_instance_type(port):
            return
        for pb_key in self._get_binding_keys(port, host):
            pb_res = MechResource(pb_key, a_const.PORT_BINDING_RESOURCE,
                                  a_const.CREATE)
            self.provision_queue.put(pb_res)
1229184
def _check_port(host, port, socket_type):
        
        if socket_type == "UDP":
            socket_type = socket.SOCK_DGRAM
        else:
            socket_type = socket.SOCK_STREAM

        for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket_type, 0, socket.AI_PASSIVE):
            af, socktype, proto, _, sa = res
            with socket.socket(af, socktype, proto) as s:
                s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                s.bind(sa)  # the port is available if bind is a success
            return True
1213122
public boolean bind ()
    {
        // open our TCP listening ports
        int successes = 0;
        for (int port : _ports) {
            try {
                acceptConnections(port);
                successes++;
            } catch (IOException ioe) {
                log.warning("Failure listening to socket", "hostname", _bindHostname,
                            "port", port, ioe);
            }
        }
        return successes > 0;
    }
280806
def detect_port(port):
    ''''''
    socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        socket_test.connect(('127.0.0.1', int(port)))
        socket_test.close()
        return True
    except:
        return False
254103
public function removeDefaultPort()
    {
        if ($this->port !== null
            && isset($this->defaultPorts[$this->getScheme()])
            && $this->defaultPorts[$this->getScheme()] === $this->port
        ) {
            $this->port = null;
        }
    }
1019658
def show_port(self, port, **_params):
        """"""
        return self.get(self.port_path % (port), params=_params)
239213
def setUp(self, port, soc, input):
        '''
        
        '''
        name = soc.getOperationName()
        bop = port.getBinding().operations.get(name)
        op = port.getBinding().getPortType().operations.get(name)

        assert op is not None, 'port has no operation %s' %name
        assert bop is not None, 'port has no binding operation %s' %name

        self.input = input
        self.op = op
        self.bop = bop
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)
834910
def validate_port(port):
    ''''''
    if not isinstance(port, (str, int)):
        raise TypeError(f'port must be an integer or string: {port}')
    if isinstance(port, str) and port.isdigit():
        port = int(port)
    if isinstance(port, int) and 0 < port <= 65535:
        return port
    raise ValueError(f'invalid port: {port}')
594029
def init(port=8813, numRetries=10, host="localhost", label="default"):
    
    _connections[label] = connect(port, numRetries, host)
    switch(label)
    return getVersion()
1177289
def find_available_port():
    
    s = socket.socket()
    s.bind(('localhost', 0))
    _address, port = s.getsockname()
    s.close()
    return port
544538
def port_bindings(self, value):
        
        if isinstance(value, (list, dict)):
                self._port_bindings = self._convert_port_bindings(value)
        elif value is None:
            self._port_bindings = None
        else:
            raise TypeError('port bindings must be a dict, list, or None. {0} was passed.'.format(type(value)))