Longman\IPTools\Ip::long2ip PHP Method

long2ip() public static method

Gets IP string representation from IP long
public static long2ip ( long $dec, $ipv6 = false ) : string
$dec long IPv4 or IPv6 long
return string If IP is valid returns IP string representation, otherwise ''.
    public static function long2ip($dec, $ipv6 = false)
    {
        $ipstr = '';
        if ($ipv6) {
            if (!function_exists('bcadd')) {
                throw new \RuntimeException('BCMATH extension not installed!');
            }
            $bin = '';
            do {
                $bin = bcmod($dec, '2') . $bin;
                $dec = bcdiv($dec, '2', 0);
            } while (bccomp($dec, '0'));
            $bin = str_pad($bin, 128, '0', STR_PAD_LEFT);
            $ip = array();
            for ($bit = 0; $bit <= 7; $bit++) {
                $bin_part = substr($bin, $bit * 16, 16);
                $ip[] = dechex(bindec($bin_part));
            }
            $ip = implode(':', $ip);
            $ipstr = inet_ntop(inet_pton($ip));
        } else {
            $ipstr = long2ip($dec);
        }
        return $ipstr;
    }

Usage Example

Example #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);
 }