Checks whether ipAddress is in IPV4 network with specified subnet
545664
public static boolean isInRangeV4(byte[] network,byte[] subnet,byte[] ipAddress)
    {
    	if(network.length!=4 || subnet.length!=4 || ipAddress.length!=4)
    		return false;    	
    	
    	return compareByteValues(network,subnet,ipAddress);
    }
1091820
private Optional<InetAddress> onSameSubnet(final InetAddress remote)
	{
		try {
			return Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
					.flatMap(ni -> ni.getInterfaceAddresses().stream())
					.filter(ia -> ia.getAddress() instanceof Inet4Address)
					.peek(ia -> logger.trace("match local address {}/{} to {}", ia.getAddress(),
							ia.getNetworkPrefixLength(), remote))
					.filter(ia -> matchesPrefix(ia.getAddress(), ia.getNetworkPrefixLength(), remote))
					.map(ia -> ia.getAddress()).findFirst();
		}
		catch (final SocketException ignore) {}
		return Optional.empty();
	}
859982
def is_ipaddress(hostname):
    
    if six.PY3 and isinstance(hostname, bytes):
        # IDN A-label bytes are ASCII compatible.
        hostname = hostname.decode('ascii')

    families = [socket.AF_INET]
    if hasattr(socket, 'AF_INET6'):
        families.append(socket.AF_INET6)

    for af in families:
        try:
            inet_pton(af, hostname)
        except (socket.error, ValueError, OSError):
            pass
        else:
            return True
    return False
1109547
function isInSubnet(string $cidr): bool {
        list ($subnet, $bits) = explode('/', $cidr);
        $subnet = ip2long($subnet);
        $mask = - 1 << (32 - $bits);
        $subnet &= $mask; // nb: in case the supplied subnet wasn't correctly aligned
        return ($this->address & $mask) == $subnet;
    }
1169611
def host_in_set (ip, hosts, nets):
    
    if ip in hosts:
        return True
    if is_valid_ipv4(ip):
        n = dq2num(ip)
        for net in nets:
            if dq_in_net(n, net):
                return True
    return False
241376
def find_ip_address(ipa_id=None, ipa_fqdn=None, ipa_ip_address=None, ipa_subnet_id=None, ipa_osi_id=None):
        
        LOGGER.debug("IPAddressService.find_ip_address")
        if (ipa_id is None or not ipa_id) and (ipa_fqdn is None or not ipa_fqdn) and \
                ((ipa_ip_address is None or not ipa_ip_address) and
                    ((ipa_subnet_id is None or not ipa_subnet_id) or (ipa_osi_id is None or not ipa_osi_id))):
            raise exceptions.ArianeCallParametersError('id and fqdn and (ip_address,(ip_subnet_id|ip_osi_id))')

        if (ipa_id is not None and ipa_id) and \
           ((ipa_fqdn is not None and ipa_fqdn) or (ipa_ip_address is not None and ipa_ip_address)):
            LOGGER.warn('IPAddressService.find_ip_address - Both id and (fqdn or ipAddress) are defined. '
                        'Will give you search on id.')
            ipa_fqdn = None
            ipa_ip_address = None
            ipa_osi_id = None
            ipa_subnet_id = None

        if (ipa_id is None or not ipa_id) and (ipa_fqdn is not None and ipa_fqdn) and \
                (ipa_ip_address is not None and ipa_ip_address):
            LOGGER.warn('IPAddressService.find_ip_address - Both fqdn and ipAddress are defined. '
                        'Will give you search on fqdn.')
            ipa_ip_address = None
            ipa_osi_id = None
            ipa_subnet_id = None

        params = None
        if ipa_id is not None and ipa_id:
            params = {'id': ipa_id}
        elif ipa_fqdn is not None and ipa_fqdn:
            params = {'fqdn': ipa_fqdn}
        elif (ipa_ip_address is not None and ipa_ip_address) and (ipa_subnet_id is not None and ipa_subnet_id):
            params = {'ipAddress': ipa_ip_address, 'subnetID': ipa_subnet_id}
        elif (ipa_ip_address is not None and ipa_ip_address) and (ipa_osi_id is not None and ipa_osi_id):
            params = {'ipAddress': ipa_ip_address, 'osiID': ipa_osi_id}

        ret = None
        if params is not None:
            args = {'http_operation': 'GET', 'operation_path': 'get', 'parameters': params}
            response = IPAddressService.requester.call(args)
            if response.rc == 0:
                ret = IPAddress.json_2_ip_address(response.response_content)
            elif response.rc != 404:
                err_msg = 'IPAddressService.find_ip_address - Problem while finding IP Address (id:' + \
                          str(ipa_id) + ', ipAddress:' + str(ipa_ip_address) \
                          + '). Reason: ' + str(response.response_content) + '-' + str(response.error_message) + \
                          " (" + str(response.rc) + ")"
                LOGGER.warning(
                    err_msg
                )

        return ret
482761
def subintf_real_ip_check_gw_port(self, gw_port, ip_addr, netmask):
        
        if gw_port is not None:
            found = False
            for i in range(len(gw_port['fixed_ips'])):
                target_ip = gw_port['fixed_ips'][i]['ip_address']
                if ip_addr == target_ip:
                    found = True
                    break
            if found is False:
                LOG.info("Subintf real IP is incorrect, deleting")
                return False
            subnet_id = gw_port['fixed_ips'][i]['subnet_id']
            subnet = next(
                sn for sn in gw_port['subnets'] if sn['id'] == subnet_id)
            target_net = netaddr.IPNetwork(subnet['cidr'])
            if netmask != str(target_net.netmask):
                LOG.info("Subintf has incorrect netmask, deleting")
                return False

            return True

        return False
822021
def network_route_exists?(network, nat_server_ip)
      routes = routes_show()
      matchdata = routes.match(route_regex(network, nat_server_ip))
      matchdata != nil
    end
535192
public static boolean isInetAddress(String host) {
		int colons = 0;
		int dots = 0;
		byte[] bytes = encodeAscii(host);

		// expect ipv6 address
		if (bytes[0] == '[') {
			return bytes[bytes.length - 1] == ']' && checkIpv6(bytes, 1, bytes.length - 1);
		}

		// assume ipv4 could be as oct, bin, dec; ipv6 - hex
		for (byte b : bytes) {
			if (b == '.') {
				dots++;
			} else if (b == ':') {
				if (dots != 0) {
					return false;
				}
				colons++;
			} else if (Character.digit(b, 16) == -1) {
				return false;
			}
		}

		if (dots < 4) {
			if (colons > 0 && colons < 8) {
				return checkIpv6(bytes, 0, bytes.length);
			}
			return checkIpv4(bytes, 0, bytes.length);
		}
		return false;
	}
1209878
def ip_check(ip, netmask_expected=False):
    
    try:
        if netmask_expected:
            if "/" not in ip:
                raise netaddr.core.AddrFormatError()
            netaddr.IPNetwork(ip)
        else:
            netaddr.IPAddress(ip)
    except netaddr.core.AddrFormatError:
        if netmask_expected:
            raise ArgsError("Not a valid CIDR (%s)" % ip)
        else:
            raise ArgsError("Not a valid IP address (%s)" % ip)
    except Exception as e:
        raise ArgsError("Invalid format: %s" % str(e))
1015892
public static boolean isInnerIP(String ipAddress) {
		boolean isInnerIp = false;
		long ipNum = NetUtil.ipv4ToLong(ipAddress);

		long aBegin = NetUtil.ipv4ToLong("10.0.0.0");
		long aEnd = NetUtil.ipv4ToLong("10.255.255.255");

		long bBegin = NetUtil.ipv4ToLong("172.16.0.0");
		long bEnd = NetUtil.ipv4ToLong("172.31.255.255");

		long cBegin = NetUtil.ipv4ToLong("192.168.0.0");
		long cEnd = NetUtil.ipv4ToLong("192.168.255.255");

		isInnerIp = isInner(ipNum, aBegin, aEnd) || isInner(ipNum, bBegin, bEnd) || isInner(ipNum, cBegin, cEnd) || ipAddress.equals(LOCAL_IP);
		return isInnerIp;
	}
1021903
def check_internal_ip(request):
    
    remote_addr = (request.META["HTTP_X_FORWARDED_FOR"] if "HTTP_X_FORWARDED_FOR" in request.META else request.META.get("REMOTE_ADDR", ""))
    return remote_addr in settings.INTERNAL_IPS
4934
public function isIPAddressInSubnet($ip_address_string)
    {
        $ip_address = ip2long($ip_address_string);
        list($start_ip, $end_ip) = $this->getIPAddressRangeAsInts();

        return $ip_address >= $start_ip && $ip_address <= $end_ip
            ? true
            : false;
    }
1360673
protected function dlstatsIPv4InNetwork($ip, $net_addr = 0, $net_mask = 0)
	{
		if ($net_mask <= 0)
		{
			return false;
		}
		if (ip2long($net_addr) === false)
		{
			return false; //no IP
		}
		//php.net/ip2long : jwadhams1 at yahoo dot com
		$ip_binary_string  = sprintf("%032b", ip2long($ip));
		$net_binary_string = sprintf("%032b", ip2long($net_addr));
		return (substr_compare($ip_binary_string, $net_binary_string, 0, $net_mask) === 0);
	}
207436
private function isIpv4InUnroutableRange(IPv4 $ip): bool
    {
        foreach ($this->unrouteableRanges as $ipRange) {
            if ($ip->matches(new Subnet($ipRange))) {
                return true;
            }
        }

        return false;
    }
937062
private boolean isIPAddress(@Nonnull String address) {
        return (InetAddressUtils.isIPv4Address(address) || InetAddressUtils.isIPv6Address(address));
    }
12823
protected function checkIPv4($UserIP = false)
	{
		// Check if IP present
		if ($UserIP === false)
		{
			return false; // No IP, no search.
		}
		// search for user bot IP-filter definitions in localconfig.php
		if (isset($GLOBALS['DLSTATS']['BOT_IPV4']))
		{
			foreach ($GLOBALS['DLSTATS']['BOT_IPV4'] as $lineleft)
			{
				$network = explode("/", trim($lineleft));
				if (! isset($network[1]))
				{
					$network[1] = 32;
				}
				if ($this->dlstatsIPv4InNetwork($UserIP, $network[0], $network[1]))
				{
					return true; // IP found
				}
			}
		}
		return false;
	}