Check whether a string matches the outline of an IPv4 address,
       allowing "*"  as a wildcard
346197
def is_valid_ip_pattern(ip):
    """"""
    ip = ip.replace('*', '1')
    try:
        socket.inet_aton(ip)
        return True
    except socket.error:
        # Not a valid IPv4 address pattern
        return False
879324
function isUrl(string){
    if (typeof string !== 'string') {
      return false;
    }

    var match = string.match(protocolAndDomainRE);
    if (!match) {
      return false;
    }

    var everythingAfterProtocol = match[1];
    if (!everythingAfterProtocol) {
      return false;
    }

    return localhostDomainRE.test(everythingAfterProtocol) ||
        nonLocalhostDomainRE.test(everythingAfterProtocol);
  }
1058332
def inet_pton(af, addr):
    """"""
    print('hello')
    if af == socket.AF_INET:
        return inet_aton(addr)
    elif af == socket.AF_INET6:
        # IPv6: The use of "::" indicates one or more groups of 16 bits of zeros.
        # We deal with this form of wildcard using a special marker. 
        JOKER = b"*"
        while b"::" in addr:
            addr = addr.replace(b"::", b":" + JOKER + b":")
        joker_pos = None 
        
        # The last part of an IPv6 address can be an IPv4 address
        ipv4_addr = None
        if b"." in addr:
            ipv4_addr = addr.split(b":")[-1]
           
        result = b""
        parts = addr.split(b":")
        for part in parts:
            if part == JOKER:
                # Wildcard is only allowed once
                if joker_pos is None:
                   joker_pos = len(result)
                else:
                   raise Exception("Illegal syntax for IP address")
            elif part == ipv4_addr: # FIXME: Make sure IPv4 can only be last part
                # FIXME: inet_aton allows IPv4 addresses with less than 4 octets 
                result += socket.inet_aton(ipv4_addr)
            else:
                # Each part must be 16bit. Add missing zeroes before decoding. 
                try:
                    result += part.rjust(4, b"0").decode("hex")
                except TypeError:
                    raise Exception("Illegal syntax for IP address")
                    
        # If there's a wildcard, fill up with zeros to reach 128bit (16 bytes) 
        if JOKER in addr:
            result = (result[:joker_pos] + b"\x00" * (16 - len(result))
                      + result[joker_pos:])
    
        if len(result) != 16:
            raise Exception("Illegal syntax for IP address")
        return result 
    else:
        raise Exception("Address family not supported")
1310489
def to_match(self):
        """"""
        self.validate()

        mark_name, field_name = self.location.get_location_name()
        validate_safe_string(mark_name)

        if field_name is None:
            return u'$matched.%s' % (mark_name,)
        else:
            validate_safe_string(field_name)
            return u'$matched.%s.%s' % (mark_name, field_name)
537307
public boolean isMatch(InetAddress inetAddress)
  {
    byte []bytes = inetAddress.getAddress();

    if (bytes.length != _address.length)
      return false;

    for (int i = 0; i < bytes.length; i++) {
      if (bytes[i] == _address[i]) {
      }
      else if (_subnetByte < i) {
        return true;
      }
      else if (i == _subnetByte) {
        return (bytes[i] & _subnetMask) == (_address[i] & _subnetMask);
      }
      else {
        return false;
      }
    }

    return true;
  }
1724
def _valid_ip(ip_address):
    '''
    
    '''

    try:
        address = ipaddress.IPv4Address(ip_address)
    except ipaddress.AddressValueError:
        return False

    if address.is_unspecified or \
        address.is_loopback or \
        address.is_link_local or \
        address.is_multicast or \
        address.is_reserved:
        return False

    return True
883257
def is_valid_ipv6 (ip):
    
    # XXX this is not complete: check ipv6 and ipv4 semantics too here
    if not (_ipv6_re.match(ip) or _ipv6_ipv4_re.match(ip) or
            _ipv6_abbr_re.match(ip) or _ipv6_ipv4_abbr_re.match(ip)):
        return False
    return True
383959
def validate(self, ip, **kwargs):
        """"""
        
        if ip is None:
            return False

        ip = stringify(ip)

        if self.IPV4_REGEX.match(ip):

            try:
                socket.inet_pton(socket.AF_INET, ip)
                return True
            except AttributeError:  # no inet_pton here, sorry
                try:
                    socket.inet_aton(ip)
                except socket.error:
                    return False
                return ip.count('.') == 3
            except socket.error:  # not a valid address
                return False

        if self.IPV6_REGEX.match(ip):
            try:
                socket.inet_pton(socket.AF_INET6, ip)
            except socket.error:  # not a valid address
                return False
            return True
713136
def valid_ipv4(ip):
    
    match =  _valid_ipv4.match(ip)
    if match is None:
        return False

    octets  = match.groups()
    if len(octets) != 4:
        return False

    first = int(octets[0])
    if first < 1 or first > 254:
        return False

    for i in range(1, 4):
        octet = int(octets[i])
        if octet < 0 or octet > 255:
            return False

    return True
20348
def validipaddr(address):
    
    try:
        octets = address.split('.')
        if len(octets) != 4:
            return False
        for x in octets:
            if not (0 <= int(x) <= 255):
                return False
    except ValueError:
        return False
    return True
31447
static boolean matchPath(String[] tokenizedPattern, String[] strDirs, boolean isCaseSensitive) {
        int patIdxStart = 0;
        int patIdxEnd = tokenizedPattern.length - 1;
        int strIdxStart = 0;
        int strIdxEnd = strDirs.length - 1;

        // up to first '**'
        while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {
            String patDir = tokenizedPattern[patIdxStart];
            if (patDir.equals(DEEP_TREE_MATCH)) {
                break;
            }
            if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) {
                return false;
            }
            patIdxStart++;
            strIdxStart++;
        }
        if (strIdxStart > strIdxEnd) {
            // String is exhausted
            for (int i = patIdxStart; i <= patIdxEnd; i++) {
                if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {
                    return false;
                }
            }
            return true;
        } else {
            if (patIdxStart > patIdxEnd) {
                // String not exhausted, but pattern is. Failure.
                return false;
            }
        }

        // up to last '**'
        while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {
            String patDir = tokenizedPattern[patIdxEnd];
            if (patDir.equals(DEEP_TREE_MATCH)) {
                break;
            }
            if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) {
                return false;
            }
            patIdxEnd--;
            strIdxEnd--;
        }
        if (strIdxStart > strIdxEnd) {
            // String is exhausted
            for (int i = patIdxStart; i <= patIdxEnd; i++) {
                if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {
                    return false;
                }
            }
            return true;
        }

        while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {
            int patIdxTmp = -1;
            for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {
                if (tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {
                    patIdxTmp = i;
                    break;
                }
            }
            if (patIdxTmp == patIdxStart + 1) {
                // '**/**' situation, so skip one
                patIdxStart++;
                continue;
            }
            // Find the pattern between padIdxStart & padIdxTmp in str between
            // strIdxStart & strIdxEnd
            int patLength = (patIdxTmp - patIdxStart - 1);
            int strLength = (strIdxEnd - strIdxStart + 1);
            int foundIdx = -1;
            strLoop:
            for (int i = 0; i <= strLength - patLength; i++) {
                for (int j = 0; j < patLength; j++) {
                    String subPat = tokenizedPattern[patIdxStart + j + 1];
                    String subStr = strDirs[strIdxStart + i + j];
                    if (!match(subPat, subStr, isCaseSensitive)) {
                        continue strLoop;
                    }
                }

                foundIdx = strIdxStart + i;
                break;
            }

            if (foundIdx == -1) {
                return false;
            }

            patIdxStart = patIdxTmp;
            strIdxStart = foundIdx + patLength;
        }

        for (int i = patIdxStart; i <= patIdxEnd; i++) {
            if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {
                return false;
            }
        }

        return true;
    }
282488
def matches_pattern(self, other):
        """"""
        matches = False
        if hasattr(other, 'addr'):
            if self.addr is None or other.addr is None:
                matches = True
            else:
                matches = self.addr == other.addr
        return matches
468183
def ipinfo_ip_check(ip):
    """"""
    if not is_IPv4Address(ip):
        return None

    response = requests.get('http://ipinfo.io/%s/json' % ip)
    return response.json()
1152720
def matchuserhome(prefix):
        
        if not prefix.startswith('~'):
            raise ValueError("prefix must start with ~")
        try: import pwd
        except ImportError:
            try: import winpwd as pwd
            except ImportError: return []
        return ['~' + u[0] for u in pwd.getpwall() if u[0].startswith(prefix[1:])]
1134446
def _explode_shorthand_ip_string(self):
        
        if isinstance(self, IPv6Network):
            ip_str = str(self.network_address)
        elif isinstance(self, IPv6Interface):
            ip_str = str(self.ip)
        else:
            ip_str = str(self)

        ip_int = self._ip_int_from_string(ip_str)
        hex_str = '%032x' % ip_int
        parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
        if isinstance(self, (_BaseNetwork, IPv6Interface)):
            return '%s/%d' % (':'.join(parts), self._prefixlen)
        return ':'.join(parts)
1076948
def is_valid_ipv4 (ip):
    
    if not _ipv4_re.match(ip):
        return False
    a, b, c, d = [int(i) for i in ip.split(".")]
    return a <= 255 and b <= 255 and c <= 255 and d <= 255
123882
public static boolean isMatchIPByPattern(String whiteList, String localIP) {
        if (StringUtils.isNotBlank(whiteList)) {
            if (StringUtils.ALL.equals(whiteList)) {
                return true;
            }
            for (String ips : whiteList.replace(',', ';').split(";", -1)) {
                try {
                    if (ips.contains(StringUtils.ALL)) { // 带通配符
                        String regex = ips.trim().replace(".", "\\.").replace("*", ".*");
                        Pattern pattern = Pattern.compile(regex);
                        if (pattern.matcher(localIP).find()) {
                            return true;
                        }
                    } else if (!isIPv4Host(ips)) { // 不带通配符的正则表达式
                        String regex = ips.trim().replace(".", "\\.");
                        Pattern pattern = Pattern.compile(regex);
                        if (pattern.matcher(localIP).find()) {
                            return true;
                        }
                    } else {
                        if (ips.equals(localIP)) {
                            return true;
                        }
                    }
                } catch (Exception e) {
                    LOGGER.warn("syntax of pattern {} is invalid", ips);
                }
            }
        }
        return false;
    }