In Ipv4 we can use ip2long
to convert it to number,
How to convert ipv6 compressed to number in PHP?
I tried inet_pton and it\'s not working.
<
Note that all answers will result in incorrect results for big IP addresses or are going through a highly complicated process to receive the actual numbers. Retrieving the actual integer value from an IPv6 address requires two things:
With both prerequisites in place conversion is as simple as:
$ip = 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff';
$int = gmp_import(inet_pton($ip));
echo $int; // 340282366920938463463374607431768211455
The binary numeric packed in_addr
representation that is returned by inet_pton is already an integer and can directly be imported to GMP, as illustrated above. There is no need for special conversions or anything.
Note that the other way around is equally simple:
$int = '340282366920938463463374607431768211455';
$ip = inet_ntop(str_pad(gmp_export($int), 16, "\0", STR_PAD_LEFT));
echo $ip; // ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
Hence building the two desired functions is as simple as:
function ipv6_to_integer($ip) {
return (string) gmp_import(inet_pton($ip));
}
function ipv6_from_integer($integer) {
return inet_ntop(str_pad(gmp_export($integer), 16, "\0", STR_PAD_LEFT));
}