Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. IpUtils.php

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\HttpFoundation

Code

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));
}

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal