Queries the system network interfaces for an IP address.
@param {boolean} loopback Whether to find a loopback address.
@param {string} family The IP family (IPv4 or IPv6). Defaults to IPv4.
@return {(string|undefined)} The located IP address or undefined.
509563
function getAddress(loopback, family) {
  let interfaces;
  if (loopback) {
    let lo = getLoInterface();
    interfaces = lo ? [lo] : null;
  }
  interfaces = interfaces || os.networkInterfaces();
  for (let key in interfaces) {
    if (!interfaces.hasOwnProperty(key)) {
      continue;
    }

    for (let ipAddress of interfaces[key]) {
      if (ipAddress.family === family && ipAddress.internal === loopback) {
        return ipAddress.address;
      }
    }
  }
  return undefined;
}
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;
}
1096970
def system_address
      ::Socket.ip_address_list.find { |address|
        address.ipv4? && !address.ipv4_loopback?
      }.ip_address rescue nil
    end
276903
public static InetAddress findLocalAddressViaNetworkInterface() {
        Enumeration<NetworkInterface> networkInterfaces;
        try {
            networkInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            return null;
        }

        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface nif = networkInterfaces.nextElement();
            for (Enumeration<InetAddress> addrEnum = nif.getInetAddresses(); addrEnum.hasMoreElements(); ) {
                InetAddress interfaceAddress = addrEnum.nextElement();
                if (useInetAddress(nif, interfaceAddress)) {
                    return interfaceAddress;
                }
            }
        }
        return null;
    }
1095800
static InetSocketAddress getRevealedLocalAddress(InetSocketAddress addr) {
        SecurityManager sm = System.getSecurityManager();
        if (addr == null || sm == null)
            return addr;

        if (!getRevealLocalAddress()) {
            // Return loopback address only if security check fails
            try{
                sm.checkConnect(addr.getAddress().getHostAddress(), -1);
                //Security check passed
            } catch (SecurityException e) {
                //Return loopback address
                addr = getLoopbackAddress(addr.getPort());
            }
        }
        return addr;
    }
736353
function idSearch( id, type, callback ) {
    if ( ! endpoints['id'].hasOwnProperty(type) ) {
        return callback(new Error('No valid type'));
    }

    var url = apiBaseUrl+endpoints['id'][type] + id;

    fetch(url, function(result) {
        callback(result);
    });
}
1316264
def add_ip(self, family='IPv4'):
        
        IP = self.cloud_manager.attach_ip(self.uuid, family)
        self.ip_addresses.append(IP)
        return IP
441670
function isIPv6(val) {
  const ipv6Block = /^[0-9A-F]{1,4}$/i;
  var blocks = val.split(':');
  var foundOmissionBlock = false; // marker to indicate ::

  // At least some OS accept the last 32 bits of an IPv6 address
  // (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says
  // that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses,
  // and '::a.b.c.d' is deprecated, but also valid.
  var foundIPv4TransitionBlock = isIPv4(blocks[blocks.length - 1]);
  var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8;

  if (blocks.length > expectedNumberOfBlocks)
    return false;

  // initial or final ::
  if (val === '::') {
    return true;
  } else if (val.substr(0, 2) === '::') {
    blocks.shift();
    blocks.shift();
    foundOmissionBlock = true;
  } else if (val.substr(val.length - 2) === '::') {
    blocks.pop();
    blocks.pop();
    foundOmissionBlock = true;
  }

  for (var i = 0; i < blocks.length; ++i) {
    // test for a :: which can not be at the string start/end
    // since those cases have been handled above
    if (blocks[i] === '' && i > 0 && i < blocks.length -1) {
      if (foundOmissionBlock)
        return false; // multiple :: in address
      foundOmissionBlock = true;
    } else if (foundIPv4TransitionBlock && i == blocks.length - 1) {
      // it has been checked before that the last
      // block is a valid IPv4 address
    } else if (!ipv6Block.test(blocks[i])) {
      return false;
    }
  }

  if (foundOmissionBlock) {
    return blocks.length >= 1;
  }
  return blocks.length === expectedNumberOfBlocks;
}
1347293
def interface_by_ipaddr(self, ipaddr):
        '''
        
        '''
        ipaddr = IPAddr(ipaddr)
        for devname,iface in self._devinfo.items():
            if iface.ipaddr == ipaddr:
                return iface
        raise KeyError("No device has IP address {}".format(ipaddr))
408838
private boolean isLocalIpAddress(InetAddress addr) {
    if (addr.isAnyLocalAddress() || addr.isLoopbackAddress())
      return true;
    try {
      return NetworkInterface.getByInetAddress(addr) != null;
    } catch (SocketException e) {
      return false;
    }
  }
1166897
function remoteAddress(req) {
        assert.ok(req, 'req');

        if(req.get("X-Real-IP")) {
            return req.get("X-Real-IP");
        }

        if (req.ip) {
            return req.ip;
        }

        if (req._remoteAddress) {
            return req._remoteAddress;
        }

        if (req.connection) {
            return req.connection.remoteAddress;
        }

        // TODO: This doesn't appear to ever get hit and causes an assertion
        // in the IP lookup due to undefined not being an IP so we need to investigate
        // what to do in this particular case (which again doesn't seem to have ever
        // actually occurred)
        return undefined;
    }
125372
public static boolean isIPv4orIPv6Address(String _ipAddress) {
        return IPV4_PATTERN.matcher(_ipAddress).matches() || IPV6_PATTERN.matcher(_ipAddress).matches();
    }
662141
def get_interfaces_ip(self):
        """"""
        interfaces_ip = {}

        interface_table = junos_views.junos_ip_interfaces_table(self.device)
        interface_table.get()
        interface_table_items = interface_table.items()

        _FAMILY_VMAP_ = {
            "inet": "ipv4",
            "inet6": "ipv6"
            # can add more mappings
        }
        _FAMILY_MAX_PREFIXLEN = {"inet": 32, "inet6": 128}

        for interface_details in interface_table_items:
            ip_network = interface_details[0]
            ip_address = ip_network.split("/")[0]
            address = napalm.base.helpers.convert(
                napalm.base.helpers.ip, ip_address, ip_address
            )
            try:
                interface_details_dict = dict(interface_details[1])
                family_raw = interface_details_dict.get("family")
                interface = py23_compat.text_type(
                    interface_details_dict.get("interface")
                )
            except ValueError:
                continue
            prefix = napalm.base.helpers.convert(
                int, ip_network.split("/")[-1], _FAMILY_MAX_PREFIXLEN.get(family_raw)
            )
            family = _FAMILY_VMAP_.get(family_raw)
            if not family or not interface:
                continue
            if interface not in interfaces_ip.keys():
                interfaces_ip[interface] = {}
            if family not in interfaces_ip[interface].keys():
                interfaces_ip[interface][family] = {}
            if address not in interfaces_ip[interface][family].keys():
                interfaces_ip[interface][family][address] = {}
            interfaces_ip[interface][family][address]["prefix_length"] = prefix

        return interfaces_ip
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);
    }
  }
986052
function(callback){
        if(source['brokerId']!='null'){
            db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){
                mqttHost = result[0]['ipAddress'];
                mqttPort = result[0]['port'];
                console.log(result);
            });
        }else{
            mqttHost = mqttPort = null;
        }
    }
413771
async function searchConnNameFromIP(ip) { // eslint-disable-line no-unused-vars
    const connNames = await listConnectionNames();
    const gipnum = ipv4.convToNum(ip);
    for (const connName of connNames) {
        const cmd = [
            'nmcli', '-f', 'IP4.ADDRESS', 'connection', 'show', connName,
        ];
        const output = await executeCommand(cmd);
        for (const line of output.split('\n')) {
            const re = line.match(/\s+([\d\.]+)\/([\d]+)/);
            if (!re) {
                continue;
            }
            const ip = ipv4.convToNum(re[1]);
            const mask = parseInt(re[2]);
            if ((ip & mask) == (gipnum & mask)) {
                return connName;
            }
        }
    }
    return null;
}
483869
def default_interface
      ip = default_ip
      Socket.getifaddrs.each do |ifaddr|
        next unless ifaddr.addr.ip?
        return ifaddr.name if ifaddr.addr.ip_address == ip
      end
      # Fall back to libpcap as last resort
      return Pcap.lookupdev
    end