parseIPv6($initial_value); } elseif(preg_match(self::$pattern_IPv4, $initial_value)) { $this->parseIPv4($initial_value); } else { $this->parseNumeric($initial_value); } } public function parseNumeric($numeric) { if(strlen($numeric) == 6) { //IPv4 $value = Numerics::numToInt($numeric); $this->ip6[6] = ($value & 0xffff0000) >> 16; $this->ip6[7] = ($value & 0x0000ffff); $this->addr_is_ipv6 = false; } else { //IPv6 $j = 0; for($i = 0; $i < strlen($numeric);) { if($numeric[$i] == "_") { $rightBlocks = (strlen($numeric) - $i - 1) / 3; $skipBlocks = 8 - $j - $rightBlocks; $j += $skipBlocks; } else { $value = Numerics::numToInt($numeric[$i].$numeric[$i+1].$numeric[$i+2]); $this->ip6[$j++] = dechex($value); $i += 3; } } } } public function parseIPv6($ipv6) { if(substr($ipv6,0,2) == "::") $ipv6 = substr($ipv6, 1); if(substr($ipv6,-2) == "::") $ipv6 = substr($ipv6, 0, -1); $ipv6blocks = explode(":", $ipv6); $j = 0; foreach($ipv6blocks as $i => $block) { if($block == "") { $skipBlocks = 8 - count($ipv6blocks); $j += $skipBlocks + 1; } else { $this->ip6[$j++] = hexdec($block); } } } public function parseIPv4($ipv4) { $ipv4blocks = explode(".",$ipv4); $this->ip6[6] = intval($ipv4blocks[0]) << 8; $this->ip6[6] |= intval($ipv4blocks[1]); $this->ip6[7] = intval($ipv4blocks[2]) << 8; $this->ip6[7] |= intval($ipv4blocks[3]); } public function isIPv6() { return $this->addr_is_ipv6; } public function getAddress() { if($this->isIPv6()) { $max_start = 0; $max_zeros = 0; $curr_zeros = 0; for ($i = 0; $i < 8; $i++) { if ($this->ip6[$i] == 0) $curr_zeros++; else if ($curr_zeros > $max_zeros) { $max_start = $i - $curr_zeros; $max_zeros = $curr_zeros; $curr_zeros = 0; } } if ($curr_zeros > $max_zeros) { $max_start = $i - $curr_zeros; $max_zeros = $curr_zeros; } $ipv6 = ""; for($i = 0; $i < 8; $i++) { if($max_zeros > 1 && $i == $max_start) { $ipv6 .= "::"; $i += $max_zeros - 1; } else { if($ipv6 != "") $ipv6 .= ":"; $ipv6 .= dechex($this->ip6[$i]); } } return $ipv6; } else { $ipv4 = array(); $ipv4[0] = ($this->ip6[6] >> 8) & 0xff; $ipv4[1] = ($this->ip6[6]) & 0xff; $ipv4[2] = ($this->ip6[7] >> 8) & 0xff; $ipv4[3] = ($this->ip6[7]) & 0xff; return implode(".", $ipv4); } } public function getNumeric() { if($this->isIPv6()) { $max_start = 0; $max_zeros = 0; $curr_zeros = 0; for ($i = 0; $i < 8; $i++) { if ($this->ip6[$i] == 0) $curr_zeros++; else if ($curr_zeros > $max_zeros) { $max_start = $i - $curr_zeros; $max_zeros = $curr_zeros; $curr_zeros = 0; } } if ($curr_zeros > $max_zeros) { $max_start = $i - $curr_zeros; $max_zeros = $curr_zeros; } $ipv6 = ""; for($i = 0; $i < 8; $i++) { if($max_zeros > 0 && $i == $max_start) { $ipv6 .= "_"; $i += $max_zeros - 1; } else { $ipv6 .= Numerics::intToNum($this->ip6[$i],3); } } return $ipv6; } else { $ipv4 = array(); $ipv4[0] = Numerics::intToNum($this->ip6[6], 3); $ipv4[1] = Numerics::intToNum($this->ip6[7], 3); return $ipv4[0].$ipv4[1]; } } } ?>