Search code examples
phpipv6gmp

Revert number to IPv6 string representation


I'm using the IP2Location database to find country codes for IPv6 addresses. They have a method to convert an IPv6 address to a (large) number which can be used to query their database.

$ipv6 = '2404:6800:4001:805::1006';
$int = inet_pton($ipv6);
$bits = 15;

$ipv6long = 0;

while($bits >= 0){
    $bin = sprintf("%08b", (ord($int[$bits])));

    if($ipv6long){
        $ipv6long = $bin . $ipv6long;
    }
    else{
        $ipv6long = $bin;
    }
    $bits--;
}
$ipv6long = gmp_strval(gmp_init($ipv6long, 2), 10);

In this case, $ipv6long would be 47875086426098177934326549022813196294.

Now Im wondering whether such a number can be reverted to the IPv6 string representation of the address. And if so, how?


Solution

  • inet_ntop() can format IPv6 addresses, but you need to convert to a packed string first (a 16 character string where each character is one byte of the number).

    function ipv6number2string($number) {
        // convert to hex
        $hex = gmp_strval(gmp_init($number, 10), 16);
        // pad to 32 chars
        $hex = str_pad($hex, 32, '0', STR_PAD_LEFT);
        // convert to a binary string
        $packed = hex2bin($hex);
        // convert to IPv6 string
        return inet_ntop($packed);
    }
    
    echo ipv6number2string(47875086426098177934326549022813196294);