Resolves the IP for a given hostname, or returns
    the input if it is already an IP.
960835
def get_host_ip(hostname, fallback=None):
    
    if is_ip(hostname):
        return hostname

    ip_addr = ns_query(hostname)
    if not ip_addr:
        try:
            ip_addr = socket.gethostbyname(hostname)
        except Exception:
            log("Failed to resolve hostname '%s'" % (hostname),
                level=WARNING)
            return fallback
    return ip_addr
958539
private LookupResult resolveAllAddressesForHostname(Object key) {

        try {
            List<ADnsAnswer> ip4Answers = new ArrayList<>();
            List<ADnsAnswer> ip6Answers = new ArrayList<>();

            // UnknownHostException is a valid case when the DNS record does not exist. Silently ignore and do not log an error.
            try {
                ip4Answers = dnsClient.resolveIPv4AddressForHostname(key.toString(), true); // Include IP version
            } catch (UnknownHostException e) {
            }

            try {
                ip6Answers = dnsClient.resolveIPv6AddressForHostname(key.toString(), true); // Include IP version
            } catch (UnknownHostException e) {
            }

            // Select answer for single value. Prefer use of IPv4 address. Only return IPv6 address if no IPv6 address found.
            final String singleValue;
            if (CollectionUtils.isNotEmpty(ip4Answers)) {
                singleValue = ip4Answers.get(0).ipAddress();
            } else if (CollectionUtils.isNotEmpty(ip6Answers)) {
                singleValue = ip6Answers.get(0).ipAddress();
            } else {
                LOG.debug("Could not resolve [A/AAAA] records hostname [{}].", key);
                return LookupResult.empty();
            }

            final LookupResult.Builder builder = LookupResult.builder();
            if (StringUtils.isNotBlank(singleValue)) {
                builder.single(singleValue);
            }

            final List<ADnsAnswer> allAnswers = new ArrayList<>();
            allAnswers.addAll(ip4Answers);
            allAnswers.addAll(ip6Answers);

            if (CollectionUtils.isNotEmpty(allAnswers)) {
                builder.multiValue(Collections.singletonMap(RESULTS_FIELD, allAnswers));
            }

            assignMinimumTTL(allAnswers, builder);

            return builder.build();
        } catch (Exception e) {
            LOG.error("Could not resolve [A/AAAA] records for hostname [{}]. Cause [{}]", key, ExceptionUtils.getRootCauseMessage(e));
            errorCounter.inc();
            return LookupResult.empty();
        }
    }
1212429
def is_ip(address):
    
    try:
        # Test to see if already an IPv4/IPv6 address
        address = netaddr.IPAddress(address)
        return True
    except (netaddr.AddrFormatError, ValueError):
        return False
1174373
public static InetAddress getIPHostAddress(String host) {
        InetAddress result = null;
        Matcher matcher = IPV4_QUADS.matcher(host);
        if (matcher == null || !matcher.matches()) {
            return result;
        }
        try {
            // Doing an Inet.getByAddress() avoids a lookup.
            result = InetAddress.getByAddress(host,
                    new byte[] {
                    (byte)(new Integer(matcher.group(1)).intValue()),
                    (byte)(new Integer(matcher.group(2)).intValue()),
                    (byte)(new Integer(matcher.group(3)).intValue()),
                    (byte)(new Integer(matcher.group(4)).intValue())});
        } catch (NumberFormatException e) {
            logger.warning(e.getMessage());
        } catch (UnknownHostException e) {
            logger.warning(e.getMessage());
        }
        return result;
    }
386425
def lookup!(nameserver=nil)
      resolver = Resolv.resolver(nameserver)
      hosts = begin
                resolver.getnames(self.address.to_s)
              rescue
                []
              end

      hosts.map! do |name|
        HostName.first_or_create(
          :address => name,
          :ip_addresses => [self]
        )
      end

      return hosts
    end
1024072
def check_ip(addr):
    '''
    
    '''

    try:
        addr = addr.rsplit('/', 1)
    except AttributeError:
        # Non-string passed
        return False

    if salt.utils.network.is_ipv4(addr[0]):
        try:
            if 1 <= int(addr[1]) <= 32:
                return True
        except ValueError:
            # Non-int subnet notation
            return False
        except IndexError:
            # No subnet notation used (i.e. just an IPv4 address)
            return True

    if salt.utils.network.is_ipv6(addr[0]):
        try:
            if 8 <= int(addr[1]) <= 128:
                return True
        except ValueError:
            # Non-int subnet notation
            return False
        except IndexError:
            # No subnet notation used (i.e. just an IPv4 address)
            return True

    return False
1300381
def host_first(self):
        """"""
        if (self.version() == 4 and self.mask > 30) or \
                (self.version() == 6 and self.mask > 126):
            return self
        else:
            return IP(self.network_long() + 1, version=self.version())
238945
def hostname(self, value):
        
        if value is None:
            value = socket.gethostname()
        self._hostname = value
268199
def _ipaddress_match(ipname, host_ip):
    
    # OpenSSL may add a trailing newline to a subjectAltName's IP address
    ip = ipaddress.ip_address(six.text_type(ipname.rstrip()))
    return ip == host_ip
16864
function getSocketAddressFromURLSafeHostname(hostname) {
    return __awaiter(this, void 0, void 0, function* () {
        // IPv4 addresses are fine
        if (net_1.isIPv4(hostname))
            return hostname;
        // IPv6 addresses are wrapped in [], which need to be removed
        if (/^\[.+\]$/.test(hostname)) {
            const potentialIPv6 = hostname.slice(1, -1);
            if (net_1.isIPv6(potentialIPv6))
                return potentialIPv6;
        }
        // This is a hostname, look it up
        try {
            const address = yield lookupAsync(hostname);
            // We found an address
            if (address)
                return address;
        }
        catch (e) {
            // Lookup failed, continue working with the hostname
        }
        return hostname;
    });
}
65579
def _ipaddress_match(ipname, host_ip):
    
    # OpenSSL may add a trailing newline to a subjectAltName's IP address
    ip = ip_address(_unicode(ipname).rstrip())
    return ip == host_ip
516825
def ResolveHostnameToIP(host, port):
  """"""
  ip_addrs = socket.getaddrinfo(host, port, socket.AF_UNSPEC, 0,
                                socket.IPPROTO_TCP)
  # getaddrinfo returns tuples (family, socktype, proto, canonname, sockaddr).
  # We are interested in sockaddr which is in turn a tuple
  # (address, port) for IPv4 or (address, port, flow info, scope id)
  # for IPv6. In both cases, we want the first element, the address.
  result = ip_addrs[0][4][0]
  # TODO: In Python 2, this value is a byte string instead of UTF-8
  # string. To ensure type correctness until support for Python 2 is dropped,
  # we always decode this value.
  if compatibility.PY2:
    result = result.decode("ascii")
  return result
381508
def as_for_ip(self, ip):
        ''''''
        if not Investigate.IP_PATTERN.match(ip):
            raise Investigate.IP_ERR

        uri = self._uris["as_for_ip"].format(ip)
        resp_json = self.get_parse(uri)

        return resp_json
851171
@Deprecated
  public static boolean verifyHostName(String hostname, String pattern) {
    String canonicalHostname;
    if (hostname.startsWith("[") && hostname.endsWith("]")) {
      // IPv6 address like [2001:db8:0:1:1:1:1:1]
      canonicalHostname = hostname.substring(1, hostname.length() - 1);
    } else {
      // This converts unicode domain name to ASCII
      try {
        canonicalHostname = IDN.toASCII(hostname);
      } catch (IllegalArgumentException e) {
        // e.g. hostname is invalid
        return false;
      }
    }
    return PGjdbcHostnameVerifier.INSTANCE.verifyHostName(canonicalHostname, pattern);
  }
921733
function resolveHost (host) {
  const defaultHost = '0.0.0.0'
  host = host || defaultHost
  const displayHost = host === defaultHost
    ? 'localhost'
    : host
  return {
    displayHost,
    host
  }
}
606340
def get_ip_on_same_subnet(self, other_compute):
        
        if other_compute == self:
            return (self.host_ip, self.host_ip)

        # Perhaps the user has correct network gateway, we trust him
        if (self.host_ip not in ('0.0.0.0', '127.0.0.1') and other_compute.host_ip not in ('0.0.0.0', '127.0.0.1')):
            return (self.host_ip, other_compute.host_ip)

        this_compute_interfaces = yield from self.interfaces()
        other_compute_interfaces = yield from other_compute.interfaces()

        # Sort interface to put the compute host in first position
        # we guess that if user specified this host it could have a reason (VMware Nat / Host only interface)
        this_compute_interfaces = sorted(this_compute_interfaces, key=lambda i: i["ip_address"] != self.host_ip)
        other_compute_interfaces = sorted(other_compute_interfaces, key=lambda i: i["ip_address"] != other_compute.host_ip)

        for this_interface in this_compute_interfaces:
            # Skip if no ip or no netmask (vbox when stopped set a null netmask)
            if len(this_interface["ip_address"]) == 0 or this_interface["netmask"] is None:
                continue
            # Ignore 169.254 network because it's for Windows special purpose
            if this_interface["ip_address"].startswith("169.254."):
                continue

            this_network = ipaddress.ip_network("{}/{}".format(this_interface["ip_address"], this_interface["netmask"]), strict=False)

            for other_interface in other_compute_interfaces:
                if len(other_interface["ip_address"]) == 0 or other_interface["netmask"] is None:
                    continue

                # Avoid stuff like 127.0.0.1
                if other_interface["ip_address"] == this_interface["ip_address"]:
                    continue

                other_network = ipaddress.ip_network("{}/{}".format(other_interface["ip_address"], other_interface["netmask"]), strict=False)
                if this_network.overlaps(other_network):
                    return (this_interface["ip_address"], other_interface["ip_address"])

        raise ValueError("No common subnet for compute {} and {}".format(self.name, other_compute.name))
521007
public static InetAddress resolveLocalNet(String host, 
                                              String netInterface) 
    	throws IOException {
        
        return resolveLocalNet(host, netInterface, null);
    }