Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace GeoIp2;
6
 
7
class 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
15
     */
16
    public static function cidr(string $ipAddress, int $prefixLen): string
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
}