download this file: ipv6.php view text/plain: ipv6.php file encoding: UTF-8 [goback]
<?php
## http://www.soucy.org/project/inet6/
##
function inet_ipv6toexpand($addr)
{
/* Check if there are segments missing, insert if necessary */
if(strpos($addr, '::') !== false)
{
$part = explode('::', $addr);
$part[0] = explode(':', $part[0]);
$part[1] = explode(':', $part[1]);
$missing = array();
for($i=0; $i<(8-(count($part[0])+count($part[1]))); $i++) array_push($missing, '0000');
$missing = array_merge($part[0], $missing);
$part = array_merge($missing, $part[1]);
}
else $part = explode(':', $addr);
/* Pad each segment until it has 4 digits */
foreach($part as &$p) { while(strlen($p) < 4) $p = '0' . $p; }
unset($p);
/* Join segments */
$result = implode(':', $part);
return (strlen($result)==39) ? $result : FALSE;
}
## https://www.drupal.org/files/issues/test.ipv4-ipv6.php.txt
## http://www.subnetonline.com/pages/subnet-calculators/ipv4-to-ipv6-converter.php
##
function inet_ipv4to6($ip)
{
static $mask = '::ffff:'; // This tells IPv6 it has an IPv4 address
$ipv6 = (strpos($ip, '::') === 0);
$ipv4 = (strpos($ip, '.') > 0);
if(!$ipv4 && !$ipv6) return FALSE;
if($ipv6 && $ipv4) $ip = substr($ip, strrpos($ip, ':')+1); // Strip IPv4 Compatibility notation
else if(!$ipv4) return $ip; // Seems to be IPv6 already?
$ip = array_pad(explode('.', $ip), 4, 0);
if(count($ip) > 4) return FALSE;
for($i=0; $i<4; $i++) if($ip[$i] > 255) return FALSE;
$part7 = base_convert(($ip[0] * 256) + $ip[1], 10, 16);
$part8 = base_convert(($ip[2] * 256) + $ip[3], 10, 16);
return $mask.$part7.':'.$part8;
}
//filter_var($ip,FILTER_VALIDATE_IP,FILTER_FLAG_IPV6)
echo $a = inet_ipv4to6('192.0.2.200'); // 2002:0:0:0:0:0:c000:2c8
echo "\n";
echo inet_ipv6toexpand($a);
?>