Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 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
     *
15
     * @ignore
16
     */
17
    public static function cidr(string $ipAddress, int $prefixLen): string
18
    {
19
        $ipBytes = inet_pton($ipAddress);
20
        $networkBytes = str_repeat("\0", \strlen($ipBytes));
21
 
22
        $curPrefix = $prefixLen;
23
        for ($i = 0; $i < \strlen($ipBytes) && $curPrefix > 0; $i++) {
24
            $b = $ipBytes[$i];
25
            if ($curPrefix < 8) {
26
                $shiftN = 8 - $curPrefix;
27
                $b = \chr(0xFF & (\ord($b) >> $shiftN) << $shiftN);
28
            }
29
            $networkBytes[$i] = $b;
30
            $curPrefix -= 8;
31
        }
32
 
33
        $network = inet_ntop($networkBytes);
34
 
35
        return "$network/$prefixLen";
36
    }
37
}