0

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.

Ganesh Babu
  • 3,482
  • 10
  • 33
  • 63
  • 2
    Possible duplicate of [PHP5 calculate IPv6 range from cidr prefix?](http://stackoverflow.com/questions/10085266/php5-calculate-ipv6-range-from-cidr-prefix) – Tomasz Kowalczyk May 31 '16 at 08:21
  • @TomaszKowalczyk I am not calculating the range here. The duplicate question you've said has the opposite solution only. – Ganesh Babu May 31 '16 at 08:22

1 Answers1

2
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

demo

splash58
  • 25,715
  • 3
  • 20
  • 32