Search code examples
phplaravel-5ipv6

How to convert IPV6 to 15 chars length integer?


I need to convert IPV6 address to 15 chars length integer so I could use IP2LOCATION database?

This is the Database "IP2LOCATION-LITE-DB1.IPV6.CSV", that I downloaded from here http://download.ip2location.com/lite/

enter image description here

I try to use this function, but it gives me very long string:

function ipv6_numeric($ip) {
   $binNum = '';
   foreach (unpack('C*', inet_pton($ip)) as $byte) {
      $binNum .= str_pad(decbin($byte), 8, "0", STR_PAD_LEFT);
   }
   return base_convert(ltrim($binNum, '0'), 2, 10);
}

ipv6_numeric('fe80:0:0:0:202:b3ff:fe1e:8329')
return "338288524927261046600406220626806860202"

Solution

  • I found this function:

    function Dot2LongIP($ipv6) {
        return (string) gmp_import(inet_pton($ipv6));
    }
    

    at this URL: https://lite.ip2location.com/faqs

    under the question: "How do I convert an IPv6 Address to an IP Number?"

    But your ipv6 address fe80:0:0:0:202:b3ff:fe1e:8329 also returns a long number: 338288524927261089654163772891438416681. Note that this result is different from what you have.

    As to the length of the result: If you actually look in the CSV file, as suggested by Nigel Ren in a comment, you will see that there are long numbers there as well.

    So, this long number is correct.