Get a free port number

No perfect solution, race conditions can occur
176150
public static function getFreePort($from, $host = 'localhost')
    {
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        $ret = $from;
        while (true) {
            if (@socket_bind($socket, $host, $ret)) {
                break;
            }
            $ret++;
            if ($ret > $from+100) {
                $this->fail('can\'t get free port number');
            }
        }
        socket_close($socket);
        return $ret;
    }
338322
def get_port_for_process(self, pid):
        """"""
        if not self._port_queue:
            raise RuntimeError('No ports being managed.')

        # Avoid an infinite loop if all ports are currently assigned.
        check_count = 0
        max_ports_to_test = len(self._port_queue)
        while check_count < max_ports_to_test:
            # Get the next candidate port and move it to the back of the queue.
            candidate = self._port_queue.pop()
            self._port_queue.appendleft(candidate)
            check_count += 1
            if (candidate.start_time == 0 or
                candidate.start_time != _get_process_start_time(candidate.pid)):
                if _is_port_free(candidate.port):
                    candidate.pid = pid
                    candidate.start_time = _get_process_start_time(pid)
                    if not candidate.start_time:
                        log.info("Can't read start time for pid %d.", pid)
                    self.ports_checked_for_last_request = check_count
                    return candidate.port
                else:
                    log.info(
                        'Port %d unexpectedly in use, last owning pid %d.',
                        candidate.port, candidate.pid)

        log.info('All ports in use.')
        self.ports_checked_for_last_request = check_count
        return 0
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
263506
def is_port_open(port, host="127.0.0.1"):
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((host, int(port)))
        s.shutdown(2)
        return True
    except Exception as e:
        return False
1196206
def port(port):
        
        value = int(port)
        if value <= 0 or value > 65535:
            raise argparse.ArgumentTypeError("%s must be between [1 - 65535]" % port)
        return value
513677
def allow_port(port, proto='tcp', direction='both'):
    '''
    
    '''

    ports = get_ports(proto=proto, direction=direction)
    direction = direction.upper()
    _validate_direction_and_proto(direction, proto)
    directions = build_directions(direction)
    results = []
    for direction in directions:
        _ports = ports[direction]
        _ports.append(port)
        results += allow_ports(_ports, proto=proto, direction=direction)
    return results
1002166
public static int getNextAvailable(int fromPort) {
        if (fromPort < MIN_PORT_NUMBER || fromPort > MAX_PORT_NUMBER) {
            throw new IllegalArgumentException("Invalid start port: "
                    + fromPort);
        }

        for (int i = fromPort; i <= MAX_PORT_NUMBER; i++) {
            if (available(i)) {
                return i;
            }
        }

        throw new NoSuchElementException("Could not find an available port "
                + "above " + fromPort);
    }
576369
function(bs, done) {
        utils.getPorts(bs.options, function(err, port) {
            if (err) {
                return utils.fail(true, err, bs.cb);
            }
            bs.debug("Found a free port: {magenta:%s", port);
            done(null, {
                options: {
                    port: port
                }
            });
        });
    }
142837
def select_port(default_port=20128):
    """"""
    import socket
    while True:
        try:
            sock = socket.socket(socket.AF_INET,
                                 socket.SOCK_STREAM,
                                 socket.IPPROTO_TCP)
#            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind( ("127.0.0.1", default_port) )
        except socket.error as _msg:  # analysis:ignore
            default_port += 1
        else:
            break
        finally:
            sock.close()
            sock = None
    return default_port
939078
function isLegalPort(port: number) : boolean {
  if (typeof port === 'string' && port.trim() === '') {
    return false;
  }
  return +port === (port >>> 0) && port >= 0 && port <= 0xFFFF;
}
1015378
def _next_port(self, port):
        
        port = 5000 + (port + 1) % 1000
        if port == self.port:
            raise DatacatsError('Too many instances running')
        return port
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
1021557
def get_port(self, adapter_number, port_number):
        
        for port in self.ports:
            if port.adapter_number == adapter_number and port.port_number == port_number:
                return port
        return None
350844
function tryRepairConnectionStart(moved, other, newDocking, points) {
  return _tryRepairConnectionSide(moved, other, newDocking, points);
}
1128068
def get_unused_port(port=None):
    """"""
    if port is None or port < 1024 or port > 65535:
        port = random.randint(1024, 65535)
    assert(1024 <= port <= 65535)
    while True:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind(('', port))  # Try to open port
        except socket.error as e:
            if e.errno in (98, 10048):  # 98, 10048 means address already bound
                return get_unused_port(None)
            raise e
        s.close()
        return port
258243
def available_ports(low=1024, high=65535, exclude_ranges=None):
    
    if exclude_ranges is None:
        exclude_ranges = []
    available = utils.ranges_to_set(UNASSIGNED_RANGES)
    exclude = utils.ranges_to_set(
        ephemeral.port_ranges() + exclude_ranges +
        [
            SYSTEM_PORT_RANGE,
            (SYSTEM_PORT_RANGE[1], low),
            (high, 65536)
        ]
    )
    return available.difference(exclude)
135250
def port_free?(host, port)
      Addrinfo.tcp(host, port).listen.close

      true
    rescue SocketError, Errno::EADDRINUSE, Errno::EACCES
      false
    end