php7 ipv6,php将ipv4/ipv6的真实ip转换为数字

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

分享到:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值