I can calculate cidr from subnet mask for ipv4 using "ip2long
" php method. How should i calculate the same for ipv6?
For example,
I can calculate the following:
255.255.252.0 => /22
How should i calculate the same for ipv6 addresses like:
ffff:ffff:ffff:ffff::
ffff:ffff:ffff:ffff:0:0:0:0
When i tried the same for ipv6 i didn't get any output?
Note: I am not calculating the ip addresses using this CIDR notation. I just want to convert the subnet mask of ipv6 to its related networking bits.
function ip6_mask2cidr($mask) {
$s = '';
if (substr($mask, -1) == ':') $mask .= '0';
if (substr($mask, 0, 1) == ':') $mask = '0' . $mask;
if (strpos($mask, '::') !== false)
$mask = str_replace('::', str_repeat(':0', 8 - substr_count($mask, ':')).':', $mask);
foreach(explode(':',$mask) as $oct) {
// The following two lines, perhaps, superfluous.
// I left them because of the paranoia :)
$oct = trim($oct);
if ($oct == '') $s .= '0000000000000000';
else $s .= str_pad(base_convert($oct, 16, 2), 16, '0', STR_PAD_LEFT);
}
return strlen($s) - strlen(rtrim($s, '0'));
}
echo ip6_mask2cidr('ffff:ffff:ffff:ffff::') . "\n"; // 64