Search result of getaddrinfo() for a non-localhost-net address
427446
def get_nonlocal_ip(host, subnet=None):
    
    try:
        ailist = socket.getaddrinfo(host, None)
    except socket.gaierror:
        raise exc.UnableToResolveError(host)
    for ai in ailist:
        # an ai is a 5-tuple; the last element is (ip, port)
        ip = ai[4][0]
        if subnet and ip_in_subnet(ip, subnet):
            LOG.info('found ip (%s) for host (%s) to be in cluster subnet (%s)' % (
                ip,
                host,
                subnet,)
            )

            return ip

        if not ip.startswith('127.'):
            if subnet:
                LOG.warning('could not match ip (%s) for host (%s) for cluster subnet (%s)' % (
                    ip,
                    host,
                    subnet,)
                )
            return ip
    raise exc.UnableToResolveError(host)
858063
def dns_lookup(host, port, afi=socket.AF_UNSPEC):
    """"""
    # XXX: all DNS functions in Python are blocking. If we really
    # want to be non-blocking here, we need to use a 3rd-party
    # library like python-adns, or move resolution onto its
    # own thread. This will be subject to the default libc
    # name resolution timeout (5s on most Linux boxes)
    try:
        return list(filter(is_inet_4_or_6,
                           socket.getaddrinfo(host, port, afi,
                                              socket.SOCK_STREAM)))
    except socket.gaierror as ex:
        log.warning('DNS lookup failed for %s:%d,'
                    ' exception was %s. Is your'
                    ' advertised.listeners (called'
                    ' advertised.host.name before Kafka 9)'
                    ' correct and resolvable?',
                    host, port, ex)
        return []
961368
function getInfo(conn){
  var params = pathParams.extractParams(conn.url);
  // Look for 'n' (new) or 'o' (open) path param.
  if (params.n) {
    return {id: params.n, existing: false};
  } else if (params.o) {
    return {id: params.o, existing: true};
  } else {
    return false;
  }
}
1098411
private static InetAddress getLocalAddress() throws UnknownHostException {
    try {
      return InetAddress.getLocalHost();  // first NIC
    } catch (Exception ignore) {
      return InetAddress.getByName(null);
    }
  }
903545
def decode_address(self, addr):
        """"""
        if _debug: Address._debug("decode_address %r (%s)", addr, type(addr))

        # start out assuming this is a local station
        self.addrType = Address.localStationAddr
        self.addrNet = None

        if addr == "*":
            if _debug: Address._debug("    - localBroadcast")

            self.addrType = Address.localBroadcastAddr
            self.addrNet = None
            self.addrAddr = None
            self.addrLen = None

        elif addr == "*:*":
            if _debug: Address._debug("   - globalBroadcast")

            self.addrType = Address.globalBroadcastAddr
            self.addrNet = None
            self.addrAddr = None
            self.addrLen = None

        elif isinstance(addr, int):
            if _debug: Address._debug("    - int")
            if (addr < 0) or (addr >= 256):
                raise ValueError("address out of range")

            self.addrAddr = struct.pack('B', addr)
            self.addrLen = 1

        elif isinstance(addr, basestring):
            if _debug: Address._debug("    - str")

            m = ip_address_mask_port_re.match(addr)
            if m:
                if _debug: Address._debug("    - IP address")

                net, addr, mask, port = m.groups()
                if not mask: mask = '32'
                if not port: port = '47808'
                if _debug: Address._debug("    - net, addr, mask, port: %r, %r, %r, %r", net, addr, mask, port)

                if net:
                    net = int(net)
                    if (net >= 65535):
                        raise ValueError("network out of range")
                    self.addrType = Address.remoteStationAddr
                    self.addrNet = net

                self.addrPort = int(port)
                self.addrTuple = (addr, self.addrPort)

                addrstr = socket.inet_aton(addr)
                self.addrIP = struct.unpack('!L', addrstr)[0]
                self.addrMask = (_long_mask << (32 - int(mask))) & _long_mask
                self.addrHost = (self.addrIP & ~self.addrMask)
                self.addrSubnet = (self.addrIP & self.addrMask)

                bcast = (self.addrSubnet | ~self.addrMask)
                self.addrBroadcastTuple = (socket.inet_ntoa(struct.pack('!L', bcast & _long_mask)), self.addrPort)

                self.addrAddr = addrstr + struct.pack('!H', self.addrPort & _short_mask)
                self.addrLen = 6

            elif ethernet_re.match(addr):
                if _debug: Address._debug("    - ethernet")

                self.addrAddr = xtob(addr, ':')
                self.addrLen = len(self.addrAddr)

            elif re.match(r"^\d+$", addr):
                if _debug: Address._debug("    - int")

                addr = int(addr)
                if (addr > 255):
                    raise ValueError("address out of range")

                self.addrAddr = struct.pack('B', addr)
                self.addrLen = 1

            elif re.match(r"^\d+:[*]$", addr):
                if _debug: Address._debug("    - remote broadcast")

                addr = int(addr[:-2])
                if (addr >= 65535):
                    raise ValueError("network out of range")

                self.addrType = Address.remoteBroadcastAddr
                self.addrNet = addr
                self.addrAddr = None
                self.addrLen = None

            elif re.match(r"^\d+:\d+$",addr):
                if _debug: Address._debug("    - remote station")

                net, addr = addr.split(':')
                net = int(net)
                addr = int(addr)
                if (net >= 65535):
                    raise ValueError("network out of range")
                if (addr > 255):
                    raise ValueError("address out of range")

                self.addrType = Address.remoteStationAddr
                self.addrNet = net
                self.addrAddr = struct.pack('B', addr)
                self.addrLen = 1

            elif re.match(r"^0x([0-9A-Fa-f][0-9A-Fa-f])+$",addr):
                if _debug: Address._debug("    - modern hex string")

                self.addrAddr = xtob(addr[2:])
                self.addrLen = len(self.addrAddr)

            elif re.match(r"^X'([0-9A-Fa-f][0-9A-Fa-f])+'$",addr):
                if _debug: Address._debug("    - old school hex string")

                self.addrAddr = xtob(addr[2:-1])
                self.addrLen = len(self.addrAddr)

            elif re.match(r"^\d+:0x([0-9A-Fa-f][0-9A-Fa-f])+$",addr):
                if _debug: Address._debug("    - remote station with modern hex string")

                net, addr = addr.split(':')
                net = int(net)
                if (net >= 65535):
                    raise ValueError("network out of range")

                self.addrType = Address.remoteStationAddr
                self.addrNet = net
                self.addrAddr = xtob(addr[2:])
                self.addrLen = len(self.addrAddr)

            elif re.match(r"^\d+:X'([0-9A-Fa-f][0-9A-Fa-f])+'$",addr):
                if _debug: Address._debug("    - remote station with old school hex string")

                net, addr = addr.split(':')
                net = int(net)
                if (net >= 65535):
                    raise ValueError("network out of range")

                self.addrType = Address.remoteStationAddr
                self.addrNet = net
                self.addrAddr = xtob(addr[2:-1])
                self.addrLen = len(self.addrAddr)

            elif netifaces and interface_re.match(addr):
                if _debug: Address._debug("    - interface name with optional port")

                interface, port = interface_re.match(addr).groups()
                if port is not None:
                    self.addrPort = int(port)
                else:
                    self.addrPort = 47808

                interfaces = netifaces.interfaces()
                if interface not in interfaces:
                    raise ValueError("not an interface: %s" % (interface,))
                if _debug: Address._debug("    - interfaces: %r", interfaces)

                ifaddresses = netifaces.ifaddresses(interface)
                if netifaces.AF_INET not in ifaddresses:
                    raise ValueError("interface does not support IPv4: %s" % (interface,))

                ipv4addresses = ifaddresses[netifaces.AF_INET]
                if len(ipv4addresses) > 1:
                    raise ValueError("interface supports multiple IPv4 addresses: %s" % (interface,))
                ifaddress = ipv4addresses[0]
                if _debug: Address._debug("    - ifaddress: %r", ifaddress)

                addr = ifaddress['addr']
                self.addrTuple = (addr, self.addrPort)
                if _debug: Address._debug("    - addrTuple: %r", self.addrTuple)

                addrstr = socket.inet_aton(addr)
                self.addrIP = struct.unpack('!L', addrstr)[0]

                if 'netmask' in ifaddress:
                    maskstr = socket.inet_aton(ifaddress['netmask'])
                    self.addrMask = struct.unpack('!L', maskstr)[0]
                else:
                    self.addrMask = _long_mask

                self.addrHost = (self.addrIP & ~self.addrMask)
                self.addrSubnet = (self.addrIP & self.addrMask)

                if 'broadcast' in ifaddress:
                    self.addrBroadcastTuple = (ifaddress['broadcast'], self.addrPort)
                else:
                    self.addrBroadcastTuple = None
                if _debug: Address._debug("    - addrBroadcastTuple: %r", self.addrBroadcastTuple)

                self.addrAddr = addrstr + struct.pack('!H', self.addrPort & _short_mask)
                self.addrLen = 6

            else:
                raise ValueError("unrecognized format")

        elif isinstance(addr, tuple):
            addr, port = addr
            self.addrPort = int(port)

            if isinstance(addr, basestring):
                if not addr:
                    # when ('', n) is passed it is the local host address, but that
                    # could be more than one on a multihomed machine, the empty string
                    # means "any".
                    addrstr = '\0\0\0\0'
                else:
                    addrstr = socket.inet_aton(addr)
                self.addrTuple = (addr, self.addrPort)

            elif isinstance(addr, (int, long)):
                addrstr = struct.pack('!L', addr & _long_mask)
                self.addrTuple = (socket.inet_ntoa(addrstr), self.addrPort)

            else:
                raise TypeError("tuple must be (string, port) or (long, port)")
            if _debug: Address._debug("    - addrstr: %r", addrstr)

            self.addrIP = struct.unpack('!L', addrstr)[0]
            self.addrMask = _long_mask
            self.addrHost = None
            self.addrSubnet = None
            self.addrBroadcastTuple = self.addrTuple

            self.addrAddr = addrstr + struct.pack('!H', self.addrPort & _short_mask)
            self.addrLen = 6

        else:
            raise TypeError("integer, string or tuple required")
1362935
def _get_ipv6addrs(self):
        
        addrs = self._get_addrs()
        ipv6addrs = addrs.get(netifaces.AF_INET6)
        if not ipv6addrs:
            return {}
        return ipv6addrs[0]
8418
def parse_address(netloc, default_port=8000):
    ''''''
    if isinstance(netloc, tuple):
        if len(netloc) != 2:
            raise ValueError('Invalid address %s' % str(netloc))
        return netloc
    #
    netloc = native_str(netloc)
    auth = None
    # Check if auth is available
    if '@' in netloc:
        auth, netloc = netloc.split('@')
    if netloc.startswith("unix:"):
        host = netloc.split("unix:")[1]
        return '%s@%s' % (auth, host) if auth else host
    # get host
    if '[' in netloc and ']' in netloc:
        host = netloc.split(']')[0][1:].lower()
    elif ':' in netloc:
        host = netloc.split(':')[0].lower()
    elif netloc == "":
        host = "0.0.0.0"
    else:
        host = netloc.lower()
    # get port
    netloc = netloc.split(']')[-1]
    if ":" in netloc:
        port = netloc.split(':', 1)[1]
        if not port.isdigit():
            raise ValueError("%r is not a valid port number." % port)
        port = int(port)
    else:
        port = default_port
    return ('%s@%s' % (auth, host) if auth else host, port)
124859
public static synchronized String getLocalIpAddress(int timeoutMs) {
    if (sLocalIP != null) {
      return sLocalIP;
    }

    try {
      InetAddress address = InetAddress.getLocalHost();
      LOG.debug("address: {} isLoopbackAddress: {}, with host {} {}", address,
          address.isLoopbackAddress(), address.getHostAddress(), address.getHostName());

      // Make sure that the address is actually reachable since in some network configurations
      // it is possible for the InetAddress.getLocalHost() call to return a non-reachable
      // address e.g. a broadcast address
      if (!isValidAddress(address, timeoutMs)) {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

        // Make getNetworkInterfaces have the same order of network interfaces as listed on
        // unix-like systems. This optimization can help avoid to get some special addresses, such
        // as loopback address"127.0.0.1", virtual bridge address "192.168.122.1" as far as
        // possible.
        if (!WINDOWS) {
          List<NetworkInterface> netIFs = Collections.list(networkInterfaces);
          Collections.reverse(netIFs);
          networkInterfaces = Collections.enumeration(netIFs);
        }

        while (networkInterfaces.hasMoreElements()) {
          NetworkInterface ni = networkInterfaces.nextElement();
          Enumeration<InetAddress> addresses = ni.getInetAddresses();
          while (addresses.hasMoreElements()) {
            address = addresses.nextElement();

            // Address must not be link local or loopback. And it must be reachable
            if (isValidAddress(address, timeoutMs)) {
              sLocalIP = address.getHostAddress();
              return sLocalIP;
            }
          }
        }

        LOG.warn("Your hostname, {} resolves to a loopback/non-reachable address: {}, "
                  +  "but we couldn't find any external IP address!",
                  InetAddress.getLocalHost().getHostName(), address.getHostAddress());
      }

      sLocalIP = address.getHostAddress();
      return sLocalIP;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
223819
public String getLocalHost()
  {
    InetAddress localAddress = addressLocal();
    
    if (localAddress != null)
      return localAddress.getHostAddress();
    else
      return null;
  }
423360
def _get_local_ip(self):
        """"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

            # Use Google Public DNS server to determine own IP
            sock.connect(('8.8.8.8', 80))

            return sock.getsockname()[0]
        except socket.error:
            try:
                return socket.gethostbyname(socket.gethostname())
            except socket.gaierror:
                return '127.0.0.1'
        finally:
            sock.close()
780422
def get_pub_addresses(names=None, timeout=10, nameserver="localhost"):
    
    addrs = []
    if names is None:
        names = ["", ]
    for name in names:
        then = datetime.now() + timedelta(seconds=timeout)
        while datetime.now() < then:
            addrs += get_pub_address(name, nameserver=nameserver)
            if addrs:
                break
            time.sleep(.5)
    return addrs
34553
def local_ip():
    """"""
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith('127.'):
        # Check eth0, eth1, eth2, en0, ...
        interfaces = [
            i + str(n) for i in ("eth", "en", "wlan") for n in xrange(3)
        ]  # :(
        for interface in interfaces:
            try:
                ip = interface_ip(interface)
                break
            except IOError:
                pass
    return ip
1165073
private static InetAddress getInetAddress(String ip) {
    if (ip == null)
      return null;

    InetAddress addr = null;
    try {
      addr = InetAddress.getByName(ip);
    } catch (UnknownHostException e) {
      Log.err(e);
      H2O.exit(-1);
    }
    return addr;
  }
873888
function getOwnIpAddresses() {
    // enumerate interfaces
    var net = os.networkInterfaces();
    var addresses = Object.keys(net)
        // flatten the array structure
        .map(function (k) { return net[k]; })
        .reduce(function (prev, cur) { return prev.concat.apply(prev, cur); }, [])
        // only use external IPv4 ones
        .filter(function (add) { return !add.internal && add.family === "IPv4"; })
        // extract address as number array
        .map(function (k) { return k.address.split(".").map(function (num) { return +num; }); })
        // ignore unconnected ones
        .filter(function (add) { return add[0] !== 169; })
        // turn the address into a string again
        .map(function (a) { return a[0] + "." + a[1] + "." + a[2] + "." + a[3]; });
    return addresses;
}
157958
function(dnsaddr) {
  var domain = getAddressDomain(dnsaddr);
  if(domain !== undefined && clients[domain] !== undefined)
    return clients[domain];
}
1053592
def getAddr (self, ifname):
        
        if sys.platform == 'darwin':
            return ifconfig_inet(ifname).get('address')
        return self._getaddr(ifname, self.SIOCGIFADDR)
297267
function getAddressNetwork (address) {
  const prefix = base58.decode(address).toString('hex').substring(0, 2).toUpperCase()
  const networkKey = findKey(networks,
    network => [network.pubKeyHash, network.scriptHash].includes(prefix))
  return networks[networkKey]
}