function IpUtils::checkIp4
Compares two IPv4 addresses. In case a subnet is given, it checks if it contains the request IP.
Parameters
string $ip IPv4 address or subnet in CIDR notation:
Return value
bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet
File
-
vendor/
symfony/ http-foundation/ IpUtils.php, line 75
Class
- IpUtils
- Http utility functions.
Namespace
Symfony\Component\HttpFoundationCode
public static function checkIp4(string $requestIp, string $ip) : bool {
$cacheKey = $requestIp . '-' . $ip . '-v4';
if (null !== ($cacheValue = self::getCacheResult($cacheKey))) {
return $cacheValue;
}
if (!filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
return self::setCacheResult($cacheKey, false);
}
if (str_contains($ip, '/')) {
[
$address,
$netmask,
] = explode('/', $ip, 2);
if ('0' === $netmask) {
return self::setCacheResult($cacheKey, false !== filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4));
}
if ($netmask < 0 || $netmask > 32) {
return self::setCacheResult($cacheKey, false);
}
}
else {
$address = $ip;
$netmask = 32;
}
if (false === ip2long($address)) {
return self::setCacheResult($cacheKey, false);
}
return self::setCacheResult($cacheKey, 0 === substr_compare(\sprintf('%032b', ip2long($requestIp)), \sprintf('%032b', ip2long($address)), 0, $netmask));
}