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

php中ipv6转纯数字和反转

发布时间:2025-04-17 18:37:29 作者:佚名 阅读:(87)

最近发现网站统计中一些IP地址的结果显示为0,经过分析发现获取到的IP地址是IPv6格式。由于IPv4的方法无法正确处理IPv6地址,导致出现问题。为了解决这个问题,可以使用PHP中的相关函数来将IPv6地址转换为纯数字形式,或者将其反转回原始的IPv6格式。接下来将为大家详细介绍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