on-demand release 4.0dev+
[moodle.git] / lib / maxmind / GeoIp2 / Util.php
CommitLineData
650f0f08
AA
1<?php
2
23b681c7
FR
3declare(strict_types=1);
4
650f0f08
AA
5namespace GeoIp2;
6
7class Util
8{
9 /**
10 * This returns the network in CIDR notation for the given IP and prefix
11 * length. This is for internal use only.
12 *
13 * @internal
14 * @ignore
650f0f08 15 */
23b681c7 16 public static function cidr(string $ipAddress, int $prefixLen): string
650f0f08
AA
17 {
18 $ipBytes = inet_pton($ipAddress);
19 $networkBytes = str_repeat("\0", \strlen($ipBytes));
20
21 $curPrefix = $prefixLen;
22 for ($i = 0; $i < \strlen($ipBytes) && $curPrefix > 0; $i++) {
23 $b = $ipBytes[$i];
24 if ($curPrefix < 8) {
25 $shiftN = 8 - $curPrefix;
26 $b = \chr(0xFF & (\ord($b) >> $shiftN) << $shiftN);
27 }
28 $networkBytes[$i] = $b;
29 $curPrefix -= 8;
30 }
31
32 $network = inet_ntop($networkBytes);
33
34 return "$network/$prefixLen";
35 }
36}