You are here

private function IpAddress::calcCidr6 in IP address fields 8

Same name and namespace in other branches
  1. 2.0.x src/IpAddress.php \Drupal\field_ipaddress\IpAddress::calcCidr6()

Calculates the IP range for an IPv6 CIDR formatted range.

See also

https://stackoverflow.com/questions/10085266/php5-calculate-ipv6-range-f...

1 call to IpAddress::calcCidr6()
IpAddress::parse in src/IpAddress.php
Find if the value given is an IP, IP range, or other.

File

src/IpAddress.php, line 218

Class

IpAddress
IpTools class.

Namespace

Drupal\field_ipaddress

Code

private function calcCidr6($ip, $prefix) {
  $start_bin = $this
    ->packIp6($ip);
  $this->start = inet_ntop($start_bin);

  // Convert the binary string to a string with hexadecimal characters.
  $start_hex = reset(unpack('H*', $start_bin));

  // Calculate flexible bits.
  $flexbits = 128 - $prefix;
  $end_hex = $start_hex;
  $pos = 31;
  while ($flexbits > 0) {

    // Get the character at this position.
    $orig = substr($end_hex, $pos, 1);

    // Convert it to an integer.
    $origval = hexdec($orig);

    // OR it with (2^flexbits)-1, with flexbits limited to 4 at a time.
    $newval = $origval | pow(2, min(4, $flexbits)) - 1;

    // Convert it back to a hexadecimal character.
    $new = dechex($newval);

    // And put that character back in the string.
    $end_hex = substr_replace($end_hex, $new, $pos, 1);

    // We processed one nibble, move to previous position.
    $flexbits -= 4;
    $pos -= 1;
  }
  $end_bin = pack('H*', $end_hex);

  // And create an IPv6 address from the binary string.
  $this->end = inet_ntop($end_bin);
}