Longman\IPTools\Ip::ip2long PHP Method

ip2long() public static method

Gets IP long representation
public static ip2long ( string $ip ) : long
$ip string IPv4 or IPv6
return long If IP is valid returns IP long representation, otherwise -1.
    public static function ip2long($ip)
    {
        $long = -1;
        if (self::isValidv6($ip)) {
            if (!function_exists('bcadd')) {
                throw new \RuntimeException('BCMATH extension not installed!');
            }
            $ip_n = inet_pton($ip);
            $bin = '';
            for ($bit = strlen($ip_n) - 1; $bit >= 0; $bit--) {
                $bin = sprintf('%08b', ord($ip_n[$bit])) . $bin;
            }
            $dec = '0';
            for ($i = 0; $i < strlen($bin); $i++) {
                $dec = bcmul($dec, '2', 0);
                $dec = bcadd($dec, $bin[$i], 0);
            }
            $long = $dec;
        } else {
            if (self::isValidv4($ip)) {
                $long = ip2long($ip);
            }
        }
        return $long;
    }

Usage Example

Beispiel #1
0
 /**
  * @test
  */
 public function test9()
 {
     $long = Ip::ip2long('192.168.1.1');
     $this->assertEquals('3232235777', $long);
     $dec = Ip::long2ip('3232235777');
     $this->assertEquals('192.168.1.1', $dec);
     $long = Ip::ip2long('fe80:0:0:0:202:b3ff:fe1e:8329');
     $this->assertEquals('338288524927261089654163772891438416681', $long);
     $dec = Ip::long2ip('338288524927261089654163772891438416681', true);
     $this->assertEquals('fe80::202:b3ff:fe1e:8329', $dec);
 }