最近发现网站统计中有一些IP的结果存储的是0,经过捕捉发现获取到的IP地址是IPv6的,使用IPv4的方法转换就会有问题,接下来为大家介绍一下php中ipv6转纯数字和反转的方法,有需要的小伙伴可以参考一下:
1、IPv6转换为数字:
(1)、方法一
function ip2long_v6($ip) {
$ip_n = inet_pton($ip);
$bin = '';
for ($bit = strlen($ip_n) - 1; $bit >= 0; $bit--) {
$bin = sprintf('%08b', ord($ip_n[$bit])) . $bin;
}
if (function_exists('gmp_init')) {
return gmp_strval(gmp_init($bin, 2), 10);
} elseif (function_exists('bcadd')) {
$dec = '0';
for ($i = 0; $i < strlen($bin); $i++) {
$dec = bcmul($dec, '2', 0);
$dec = bcadd($dec, $bin[$i], 0);
}
return $dec;
} else {
trigger_error('GMP or BCMATH extension not installed!', E_USER_ERROR);
}
}
echo ip2long_v6('2409:8962:f08:bc70:dd8d:3271:9735:1afb');
//输出结果为38位数字:47901724979112247990722674108375833339
(2)、方法二(需要在php.ini中开启php_gmp扩展)
function ip2long_v6($ip){
$ip_n = inet_pton($ip);
$bits = 15; // 16 x 8 bit = 128bit
$ipv6long = '';
while ($bits >= 0) {
$bin = sprintf("%08b", (ord($ip_n[$bits])));
$ipv6long = $bin . $ipv6long;
$bits--;
}
return gmp_strval(gmp_init($ipv6long, 2), 10);
}
2、将IPv6转换后数字反转成IP:
function long2ip_v6($dec) {
if(strlen($dec) > 10){
if (function_exists('gmp_init')) {
$bin = gmp_strval(gmp_init($dec, 10), 2);
} elseif (function_exists('bcadd')) {
$bin = '';
do {
$bin = bcmod($dec, '2') . $bin;
$dec = bcdiv($dec, '2', 0);
} while (bccomp($dec, '0'));
} else {
trigger_error('GMP or BCMATH extension not installed!', E_USER_ERROR);
}
$bin = str_pad($bin, 128, '0', STR_PAD_LEFT);
$ip = array();
for ($bit = 0; $bit <= 7; $bit++) {
$bin_part = substr($bin, $bit * 16, 16);
$ip[] = dechex(bindec($bin_part));
}
$ip = implode(':', $ip);
}else{
$ip = long2ip($dec);
}
return inet_ntop(inet_pton($ip));
}
echo long2ip_v6('47901724979112247990722674108375833339');
//输出结果:2409:8962:f08:bc70:dd8d:3271:9735:1afb
