Bootstrap the server by connecting to other known nodes in the network.

        Args:
            addrs: A `list` of (ip, port) `tuple` pairs.  Note that only IP
                   addresses are acceptable - hostnames will cause an error.
549032
async def bootstrap(self, addrs):
        
        log.debug("Attempting to bootstrap node with %i initial contacts",
                  len(addrs))
        cos = list(map(self.bootstrap_node, addrs))
        gathered = await asyncio.gather(*cos)
        nodes = [node for node in gathered if node is not None]
        spider = NodeSpiderCrawl(self.protocol, self.node, nodes,
                                 self.ksize, self.alpha)
        return await spider.find()
359029
def server_add(s_name, s_ip, s_state=None, **connection_args):
    '''
    
    '''
    ret = True
    if server_exists(s_name, **connection_args):
        return False
    nitro = _connect(**connection_args)
    if nitro is None:
        return False
    server = NSServer()
    server.set_name(s_name)
    server.set_ipaddress(s_ip)
    if s_state is not None:
        server.set_state(s_state)
    try:
        NSServer.add(nitro, server)
    except NSNitroError as error:
        log.debug('netscaler module error - NSServer.add() failed: %s', error)
        ret = False
    _disconnect(nitro)
    return ret
695568
async def _check_ip(self, addr):
        

        tasks = []
        for provider in self.providers:
            tasks.append(self.dnsbl_request(addr, provider))
        results = await asyncio.gather(*tasks)
        return DNSBLResult(addr=addr, results=results)
990368
def split_addrs(addrs):
    '''
    '''
    splitted = {}
    for addr in addrs:
        host, port, _ = _addr_key(addr)
        if host not in splitted:
            splitted[host] = {}
        if port not in splitted[host]:
            splitted[host][port] = []
        splitted[host][port].append(addr)
    return splitted
1041820
private CommunicationParam buildParams(String addr) {
        CommunicationParam params = new CommunicationParam();
        String[] strs = StringUtils.split(addr, ":");
        if (strs == null || strs.length != 2) {
            throw new IllegalArgumentException("addr example: 127.0.0.1:1099");
        }
        InetAddress address = null;
        try {
            address = InetAddress.getByName(strs[0]);
        } catch (UnknownHostException e) {
            throw new CommunicationException("addr_error", "addr[" + addr + "] is unknow!");
        }
        params.setIp(address.getHostAddress());
        params.setPort(Integer.valueOf(strs[1]));
        return params;
    }
1259435
def in_subnet(cidr, addrs=None):
    
    for address in addrs:
        if ip_in_subnet(address, cidr):
            return True
    return False
423017
def connect(self, addr):
        """"""
        # Here we assume that the socket is client-side, and not
        # connected at the time of the call.  We connect it, then wrap it.
        if self._sslobj:
            raise ValueError("attempt to connect already-connected SSLSocket!")
        socket.connect(self, addr)
        if six.PY3:
            self._sslobj = self.context._wrap_socket(self._sock, False, self.server_hostname)
        else:
            if self.ciphers is None:
                self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
                                            self.cert_reqs, self.ssl_version,
                                            self.ca_certs)
            else:
                self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
                                            self.cert_reqs, self.ssl_version,
                                            self.ca_certs, self.ciphers)
        if self.do_handshake_on_connect:
            self.do_handshake()
753865
def connect(self, address, **kwargs):
        
        if self._transport:
            raise RuntimeError('already connected')
        kwargs.setdefault('timeout', self._timeout)
        conn = create_connection(self._protocol_factory, address, **kwargs)
        self._transport = conn[0]
        self._transport._log = self._log
        self._protocol = conn[1]
        self._protocol._log = self._log
965584
def allow_address_pairs(session, network, subnet):
    
    nclient = neutron.Client('2', session=session,
                             region_name=os.environ['OS_REGION_NAME'])
    ports = nclient.list_ports()
    ports_to_update = filter(
        lambda p: p['network_id'] == network['id'],
        ports['ports'])
    logger.info('[nova]: Allowing address pairs for ports %s' %
                list(map(lambda p: p['fixed_ips'], ports_to_update)))
    for port in ports_to_update:
        try:
            nclient.update_port(port['id'], {
                'port': {
                    'allowed_address_pairs': [{
                        'ip_address': subnet
                        }]
                    }
                })
        except Exception:
            # NOTE(msimonin): dhcp and router interface port
            # seems to have enabled_sec_groups = False which
            # prevent them to be updated, just throw a warning
            # a skip them
            logger.warn("Can't update port %s" % port)
1315402
def get_ip(host):
    '''
    
    '''
    hosts = _list_hosts()
    if not hosts:
        return ''
    # Look for the op
    for addr in hosts:
        if host in hosts[addr]:
            return addr
    # ip not found
    return ''
393459
def add_ipv6addr(self, ipv6addr):
        
        for addr in self.ipv6addrs:
            if ((isinstance(addr, dict) and addr['ipv6addr'] == ipv6addr) or
                (isinstance(addr, HostIPv4) and addr.ipv6addr == ipv6addr)):
                raise ValueError('Already exists')
        self.ipv6addrs.append({'ipv6addr': ipv6addr})
718029
def _resolve_addrs(straddrs, port, ignore_unavailable=False, protocols=[socket.AF_INET, socket.AF_INET6]):
    

    res = []
    for sa in straddrs:
        try:
            ais = socket.getaddrinfo(sa, port)
            for ai in ais:
                if ai[0] in protocols:
                    res.append((ai[0], ai[4], ai[0], ai[4][0]))
                    break
            else:
                # Try to convert from IPv4 to IPv6
                ai = ais[0]
                if ai[0] == socket.AF_INET and socket.AF_INET6 in protocols:
                    to = socket.getaddrinfo('::ffff:' + ai[4][0], port, socket.AF_INET6)[0][4]
                    res.append((socket.AF_INET6, to, ai[0], ai[4][0]))
        except socket.gaierror:
            if not ignore_unavailable:
                raise

    return res
323684
def is_same_address(addr1, addr2):
    
    hostport1 = addr1.split(":")
    hostport2 = addr2.split(":")

    return (is_same_host(hostport1[0], hostport2[0]) and
            hostport1[1] == hostport2[1])
787957
def nameservers_for_device(n_ip)
      nameservers = []
      raw_nameservers = ENV["RS_IP#{n_ip}_NAMESERVERS"].to_s.strip.split(/[, ]+/)
      raw_nameservers.each do |nameserver|
        if valid_ipv4?(nameserver)
          nameservers << nameserver
        else
          # Non-fatal error, we only need one working
          logger.error("Invalid nameserver #{nameserver} for interface##{n_ip}")
        end
      end
      # Also a non-fatal error, DHCP or another interface specify nameservers and we're still good
      logger.warn("No valid nameservers specified for static interface##{n_ip}") unless nameservers.length > 0
      nameservers
    end
1001367
def send(_dict, addr):
        
        # TODO(rbtz@): IPv6 support
        udp_sock = socket(AF_INET, SOCK_DGRAM)
        # TODO(rbtz@): Add batch support
        for item in _dict.items():
            udp_sock.sendto(":".join(item).encode('utf-8'), addr)
854117
def lookup_from_headers(cls, headers):
        

        # A single address, set by this server, returned as an Array
        remote_addr = cls.ips_from(headers.get("REMOTE_ADDR"))

        # Could be a CSV list and/or repeated headers that were concatenated.
        forwarded_ips = cls.ips_from(headers.get("HTTP_X_FORWARDED_FOR"))
        client_ips = cls.ips_from(headers.get("HTTP_CLIENT_IP"))

        # We assume these things about the IP headers:
        #
        #   - X-Forwarded-For will be a list of IPs, one per proxy, or blank.
        #       in order: `client,proxy1,proxy2`
        #   - Client-Ip is propagated from the outermost proxy, or is blank
        #   - REMOTE_ADDR will be the IP that made the request to this server
        #
        # X-Forwarded-For and Client-Ip shouldn't be set at the same time, but
        # if they are, use the one in Forwarded
        ips = forwarded_ips + client_ips + remote_addr

        try:
            return ips[0]
        except IndexError:
            return None
1195019
def add_ip_to_net(networks, host):
    
    for network in networks:
        if host['ipaddr'] in network['network']:
            network['hosts'].append(host)
            return