当前位置:首页 > PHP教程 >

php中ipv6转纯数字和反转

发布时间:2023-12-24 12:06:35 作者:佚名 阅读:(51)

最近发现网站统计中有一些IP的结果存储的是0,经过捕捉发现获取到的IP地址是IPv6的,运用IPv4的办法转换就会有问题,接下来云梦编程为大家详细的介绍一下php中ipv6转纯数字和反转的办法,有需要的小伙伴可以参考一下:

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:8a62:5b54:9bf0:15d0:d2b:5f07:e7b5');
//输出结果为38位数字:47901745285134437259802640864852305845

    (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('47901745285134437259802640864852305845');
//输出结果:2409:8a62:5b54:9bf0:15d0:d2b:5f07:e7b5


以上就是云梦编程为大家介绍的关于php中ipv6转纯数字和反转的方法,了解更多相关文章请关注云梦编程网!

© 2023 - 云梦编程网 版权所有 鲁ICP备2021017318号-4