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.
<
A version of the answer by boen_robot which avoids the overflow issue, using BC Math if available.
function ipv62numeric($ip)
{
$str = '';
foreach (unpack('C*', inet_pton($ip)) as $byte) {
$str .= str_pad(decbin($byte), 8, '0', STR_PAD_LEFT);
}
$str = ltrim($str, '0');
if (function_exists('bcadd')) {
$numeric = 0;
for ($i = 0; $i < strlen($str); $i++) {
$right = base_convert($str[$i], 2, 10);
$numeric = bcadd(bcmul($numeric, 2), $right);
}
$str = $numeric;
} else {
$str = base_convert($str, 2, 10);
}
return $str;
}
Example:
echo ipv62numeric('2001:11ff:ffff::f');
Will return "42540853245347499564798372846648688655" as a string, which is the correct answer.