Ensures an ip address is both a valid IP and does not fall within
a private network range.
971298
public static function validateIpAddress($ipAddress) {
        if (strtolower($ipAddress) === 'unknown') {
            return false;
        }

        // generate ipv4 network address
        $ipAddress = ip2long($ipAddress);

        // if the ip is set and not equivalent to 255.255.255.255
        if ($ipAddress !== false && $ipAddress !== -1) {
            // make sure to get unsigned long representation of ip
            // due to discrepancies between 32 and 64 bit OSes and
            // signed numbers (ints default to signed in PHP)
            $ipAddress = sprintf('%u', $ipAddress);
            // do private network range checking
            if ($ipAddress >= 0 && $ipAddress <= 50331647) {
                return false;
            }
            if ($ipAddress >= 167772160 && $ipAddress <= 184549375) {
                return false;
            }
            if ($ipAddress >= 2130706432 && $ipAddress <= 2147483647) {
                return false;
            }
            if ($ipAddress >= 2851995648 && $ipAddress <= 2852061183) {
                return false;
            }
            if ($ipAddress >= 2886729728 && $ipAddress <= 2887778303) {
                return false;
            }
            if ($ipAddress >= 3221225984 && $ipAddress <= 3221226239) {
                return false;
            }
            if ($ipAddress >= 3232235520 && $ipAddress <= 3232301055) {
                return false;
            }
            if ($ipAddress >= 4294967040) {
                return false;
            }
        }
        return true;
    }
1048467
def is_valid_ipv6_prefix(ipv6_prefix):
    """"""

    # Validate input type
    if not isinstance(ipv6_prefix, str):
        return False

    tokens = ipv6_prefix.split('/')
    if len(tokens) != 2:
        return False

    # Validate address/mask and return
    return is_valid_ipv6(tokens[0]) and is_valid_ip_prefix(tokens[1], 128)
389892
def is_valid_ip(ip: str) -> bool:
    
    if not ip or "\x00" in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(
            ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST
        )
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True
1099508
def check_ip(original_ip):
    '''
    
    ''' 
    ip = original_ip.strip()
    parts = ip.split('.')
    if len(parts) != 4:
        return None
    for p in parts:
        try:
            p = int(p)
            if (p < 0) or (p > 255):
                return None
        except:
            return None
    return ip
586096
def deny(self, ip):
        
        self.blacklist.append(ip)
        self.whitelist.clear()
1061292
public function isValidIP4NoPrivate(string $ipAddress): bool
    {
        return (bool) filter_var(
            $ipAddress,
            FILTER_VALIDATE_IP,
            FILTER_FLAG_IPV4
            | FILTER_FLAG_NO_PRIV_RANGE
            | FILTER_FLAG_NO_RES_RANGE
        );
    }
1024190
def check_valid_ip_or_cidr(val, return_as_cidr=False):
    
    is_ip = True
    if "/" in val:
        ip_check(val, netmask_expected=True)
        is_ip = False
    else:
        ip_check(val, netmask_expected=False)

    if return_as_cidr and is_ip:
        # Convert a plain IP to a CIDR
        if val == "0.0.0.0":
            # Special case for the default route
            val = "0.0.0.0/0"
        else:
            val = "%s/32" % val

    try:
        ipaddress.IPv4Network(unicode(val))
    except Exception as e:
        raise ArgsError("Not a valid network: %s" % str(e))

    return val
510081
def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]):
    
    for ip in ips:
        if isinstance(ip, ipaddress.IPv4Address):
            allowed_ips.add(ip)
        elif isinstance(ip, str):
            allowed_ips.add(ipaddress.IPv4Address(ip))
        elif isinstance(ip, ipaddress.IPv4Network):
            allowed_ips.update(ip.hosts())
        else:
            raise ValueError(f"Bad type of ipaddress: {type(ip)} ('{ip}')")
1283664
def ip_between(ip, start, finish):
    """"""

    if is_IPv4Address(ip) and is_IPv4Address(start) and is_IPv4Address(finish):
        return IPAddress(ip) in IPRange(start, finish)
    else:
        return False
1305880
def _valid_ip6(ip_address):
    '''
    
    '''

    # Validate IPv6 address
    try:
        address = ipaddress.IPv6Address(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

    if address.ipv4_mapped is not None:
        return False

    return True
1140148
def user_domain_match(A, B):
    
    A = A.lower()
    B = B.lower()
    if not (liberal_is_HDN(A) and liberal_is_HDN(B)):
        if A == B:
            # equal IP addresses
            return True
        return False
    initial_dot = B.startswith(".")
    if initial_dot and A.endswith(B):
        return True
    if not initial_dot and A == B:
        return True
    return False
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
1365053
protected function validateIp($ip)
    {
        $filter = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
        return filter_var($ip, FILTER_VALIDATE_IP, $filter);
    }
1209603
def ip_check(*args, func=None):
    """"""
    func = func or inspect.stack()[2][3]
    for var in args:
        if not isinstance(var, ipaddress._IPAddressBase):
            name = type(var).__name__
            raise IPError(
                f'Function {func} expected IP address, {name} got instead.')
1326745
def __ip_addr(addr, address_family=socket.AF_INET):
    '''
    
    '''
    mask_max = '32'
    if address_family == socket.AF_INET6:
        mask_max = '128'

    try:
        if '/' not in addr:
            addr = '{addr}/{mask_max}'.format(addr=addr, mask_max=mask_max)
    except TypeError:
        return False

    ip, mask = addr.rsplit('/', 1)

    # Verify that IP address is valid
    try:
        socket.inet_pton(address_family, ip)
    except socket.error:
        return False

    # Verify that mask is valid
    try:
        mask = int(mask)
    except ValueError:
        return False
    else:
        if not 1 <= mask <= int(mask_max):
            return False

    return True
1158821
def hasIP(self, ip):
        """"""

        for f in self.features:
            if (f.prop.startswith("net_interface.") and
                    f.prop.endswith(".ip") and f.value == ip):
                return True
        return False
446901
private function validateInputs($ip, $network_size)
    {
        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
            throw new \UnexpectedValueException("IP address $ip not valid.");
        }
        if (( $network_size < 1 ) || ( $network_size > 32 )) {
            throw new \UnexpectedValueException("Network size $network_size not valid.");
        }
    }