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

Breadcrumb

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

function IpUtils::anonymize

Anonymizes an IP/IPv6.

Removes the last bytes of IPv4 and IPv6 addresses (1 byte for IPv4 and 8 bytes for IPv6 by default).

Parameters

int<0, 4> $v4Bytes:

int<0, 16> $v6Bytes:

File

vendor/symfony/http-foundation/IpUtils.php, line 186

Class

IpUtils
Http utility functions.

Namespace

Symfony\Component\HttpFoundation

Code

public static function anonymize(string $ip) : string {
    $v4Bytes = 1 < \func_num_args() ? func_get_arg(1) : 1;
    $v6Bytes = 2 < \func_num_args() ? func_get_arg(2) : 8;
    if ($v4Bytes < 0 || $v6Bytes < 0) {
        throw new \InvalidArgumentException('Cannot anonymize less than 0 bytes.');
    }
    if ($v4Bytes > 4 || $v6Bytes > 16) {
        throw new \InvalidArgumentException('Cannot anonymize more than 4 bytes for IPv4 and 16 bytes for IPv6.');
    }
    $wrappedIPv6 = false;
    if (str_starts_with($ip, '[') && str_ends_with($ip, ']')) {
        $wrappedIPv6 = true;
        $ip = substr($ip, 1, -1);
    }
    $mappedIpV4MaskGenerator = function (string $mask, int $bytesToAnonymize) {
        $mask .= str_repeat('ff', 4 - $bytesToAnonymize);
        $mask .= str_repeat('00', $bytesToAnonymize);
        return '::' . implode(':', str_split($mask, 4));
    };
    $packedAddress = inet_pton($ip);
    if (4 === \strlen($packedAddress)) {
        $mask = rtrim(str_repeat('255.', 4 - $v4Bytes) . str_repeat('0.', $v4Bytes), '.');
    }
    elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff:ffff'))) {
        $mask = $mappedIpV4MaskGenerator('ffff', $v4Bytes);
    }
    elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff'))) {
        $mask = $mappedIpV4MaskGenerator('', $v4Bytes);
    }
    else {
        $mask = str_repeat('ff', 16 - $v6Bytes) . str_repeat('00', $v6Bytes);
        $mask = implode(':', str_split($mask, 4));
    }
    $ip = inet_ntop($packedAddress & inet_pton($mask));
    if ($wrappedIPv6) {
        $ip = '[' . $ip . ']';
    }
    return $ip;
}

API Navigation

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