php将ipv4/ipv6的真实ip转换为数字
2020-09-15
59
方法一:**
* Description: 此函数用来将Ip转换为数字,便于存储
* ip:IPv6、Ipv6
* PS:需开启php_gmp扩展
*/
function ip2long_int($ip){
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return sprintf('%u',ip2long($ip));
} else if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$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);
}
}
方法二:/**
* description: 此函数用来将Ip转换为数字,便于存储
* ip:IPv4、IPv6
*/
function ip2long_int($ip){
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return sprintf('%u',ip2long($ip));
} else if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$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
$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);
}
}
}
注意:由于IPv6转换后的字符串长度是38位的数字,需要将数据库中的字段类型转为char或varchar类型。
将数字在转换为Ip方法function long2ip_varchar($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);
return inet_ntop(inet_pton($ip));
}else{
return long2ip($dec);
}
}
echo long2ip_varchar('47901724979112247990722674108375833339');
//输出结果:2409:8962:f08:bc70:dd8d:3271:9735:1afb
分享到: