Creates a regular expression to match a hostname or ip address
321650
def hostname_or_ip_address(blank = false)
      regexp = Regexp.union(hostname, ip_address)
      add_blank_option(regexp, blank)
    end
808114
def _isbtaddr(address):
    
    # Define validity regex. Accept either ":" or "-" as separators.
    global _validbtaddr
    if _validbtaddr is None:
        import re
        _validbtaddr = re.compile("((\d|[a-f]){2}(:|-)){5}(\d|[a-f]){2}",
                re.IGNORECASE)
    import types
    if not isinstance(address, str):
        return False
    return _validbtaddr.match(address) is not None
468464
def hosts2map (hosts):
    
    hostset = set()
    nets = []
    for host in hosts:
        if _host_cidrmask_re.match(host):
            host, mask = host.split("/")
            mask = int(mask)
            if not is_valid_cidrmask(mask):
                log.error(LOG_CHECK,
                          "CIDR mask %d is not a valid network mask", mask)
                continue
            if not is_valid_ipv4(host):
                log.error(LOG_CHECK, "host %r is not a valid ip address", host)
                continue
            nets.append(dq2net(host, cidr2mask(mask)))
        elif _host_netmask_re.match(host):
            host, mask = host.split("/")
            if not is_valid_ipv4(host):
                log.error(LOG_CHECK, "host %r is not a valid ip address", host)
                continue
            if not is_valid_ipv4(mask):
                log.error(LOG_CHECK,
                          "mask %r is not a valid ip network mask", mask)
                continue
            nets.append(dq2net(host, netmask2mask(mask)))
        elif is_valid_ip(host):
            hostset.add(expand_ip(host)[0])
        else:
            hostset |= set(resolve_host(host))
    return (hostset, nets)
500507
def validate_host_ip(ips, subnets):
    
    # Make sure we prune ``None`` arguments
    subnets = [s for s in subnets if s is not None]
    validate_one_subnet = len(subnets) == 1

    def ip_in_one_subnet(ips, subnet):
        """ ensure an ip exists in at least one subnet """
        for ip in ips:
            if net.ip_in_subnet(ip, subnet):
                return True
        return False

    for subnet in subnets:
        if ip_in_one_subnet(ips, subnet):
            if validate_one_subnet:
                return
            else:  # keep going to make sure the other subnets are ok
                continue
        else:
            msg = "subnet (%s) is not valid for any of the ips found %s" % (subnet, str(ips))
            raise RuntimeError(msg)
716909
function(hostname) {
    const buf = pslBuffer8;
    if ( hostname === hostnameArg ) { return buf[LABEL_INDICES_SLOT]; }
    if ( hostname === null || hostname.length === 0 ) {
        hostnameArg = '';
        return (buf[LABEL_INDICES_SLOT] = 0);
    }
    hostname = hostname.toLowerCase();
    hostnameArg = hostname;
    let n = hostname.length;
    if ( n > 255 ) { n = 255; }
    buf[LABEL_INDICES_SLOT] = n;
    let i = n;
    let j = LABEL_INDICES_SLOT + 1;
    while ( i-- ) {
        const c = hostname.charCodeAt(i);
        if ( c === 0x2E /* '.' */ ) {
            buf[j+0] = i + 1;
            buf[j+1] = i;
            j += 2;
        }
        buf[i] = c;
    }
    buf[j] = 0;
    return n;
}
1263802
def _build_query(self, ip_address):
        
        return '{}.{}.{}'.format(
            self.key, self._reverse_ip(ip_address), DNSBL_SUFFIX)
462890
def validate_linux_host_name(namespace):
    
    # https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
    rfc1123_regex = re.compile(r'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$')  # pylint:disable=line-too-long
    found = rfc1123_regex.findall(namespace.name)
    if not found:
        raise CLIError('--name cannot exceed 63 characters and can only contain '
                       'letters, numbers, or dashes (-).')
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;
    });
}
983304
def get_name(self, host_name):
        
        if wildcard_match(self._pattern, host_name):
            return host_name
        else:
            return self._fallback
802279
def regex(self, protocols, localhost=True):
        
        p = r"^"

        # protocol
        p += r"(?:(?:(?:{}):)?//)".format('|'.join(protocols))

        # basic auth (optional)
        p += r"(?:\S+(?::\S*)?@)?"

        p += r"(?:"

        # ip exclusion: private and local networks
        p += r"(?!(?:10|127)(?:\.\d{1,3}){3})"
        p += r"(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})"
        p += r"(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})"

        # ip excluding loopback (0.0.0.0), reserved space (244.0.0.0)
        # and network/broadcast addresses
        p += r"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])"
        p += r"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}"
        p += r"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))"
        p += r"|"

        # hostname
        p += r"(?:"
        p += r"(?:"
        p += r"[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?"
        p += r"[a-z0-9\u00a1-\uffff]"
        p += r"\." if not localhost else r"[\.]?|localhost"


        p += r")+"

        # tld
        p += r"(?:[a-z\u00a1-\uffff]{2,}\.?)"
        p += r")"

        # port (optional)
        p += r"(?::\d{2,5})?"

        # path (optional)
        p += r"(?:[/?#]\S*)?"

        p += r"$"
        return p
877573
def matches_ip(self, ip):
        """"""

        # Check the cache if caching is enabled
        if self.cache is not None:
            matches_ip = self.cache.get(ip)
            if matches_ip is not None:
                return matches_ip

        # Query MongoDB to see if the IP is blacklisted
        matches_ip = IPNetwork.matches_ip(
            ip, read_preference=self.read_preference)

        # Cache the result if caching is enabled
        if self.cache is not None:
            self.cache[ip] = matches_ip

        return matches_ip
459355
def splithost(url):
    """"""
    global _hostprog
    if _hostprog is None:
        import re
        _hostprog = re.compile('^//([^/?]*)(.*)$')

    match = _hostprog.match(url)
    if match:
        host_port = match.group(1)
        path = match.group(2)
        if path and not path.startswith('/'):
            path = '/' + path
        return host_port, path
    return None, url
235777
def patch_match_hostname():
    """"""


    _old_match_hostname = ssl.match_hostname

    def _new_match_hostname(cert, hostname):
        if hostname.endswith('.s3.amazonaws.com'):
            pos = hostname.find('.s3.amazonaws.com')
            hostname = hostname[:pos].replace('.', '') + hostname[pos:]
        return _old_match_hostname(cert, hostname)

    ssl.match_hostname = _new_match_hostname
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);
  }
243046
def url_to_host(url):
    

    regex_url = r"([a-z][a-z0-9+\-.]*://)?" + \
                r"([a-z0-9\-._~%!$&'()*+,;=]+@)?" + \
                r"([a-z0-9\-._~%]+" + \
                r"|\[[a-z0-9\-._~%!$&'()*+,;=:]+\])?" + \
                r"(:(?P<port>[0-9]+))?"

    m = re.match(regex_url, url, re.IGNORECASE)
    if m and m.group(3):
        return url[m.start(3): m.end(3)]
    else:
        raise ValueError("URL without a valid host or ip")
1101574
static void ensureHostnamePatternMatchesDefaultHostname(String hostnamePattern, String defaultHostname) {
        if ("*".equals(hostnamePattern)) {
            return;
        }

        // Pretty convoluted way to validate but it's done only once and
        // we don't need to duplicate the pattern matching logic.
        final DomainNameMapping<Boolean> mapping =
                new DomainNameMappingBuilder<>(Boolean.FALSE).add(hostnamePattern, Boolean.TRUE).build();

        if (!mapping.map(defaultHostname)) {
            throw new IllegalArgumentException(
                    "defaultHostname: " + defaultHostname +
                    " (must be matched by hostnamePattern: " + hostnamePattern + ')');
        }
    }
1245943
def _ipaddress_match(ipname, host_ip):
    
    # OpenSSL may add a trailing newline to a subjectAltName's IP address
    # Divergence from upstream: ipaddress can't handle byte str
    ip = ipaddress.ip_address(_to_unicode(ipname).rstrip())
    return ip == host_ip