Php convert ipv6 to number

前端 未结 7 1111
醉话见心
醉话见心 2021-01-31 20:53

In Ipv4 we can use ip2long to convert it to number,

How to convert ipv6 compressed to number in PHP?

I tried inet_pton and it\'s not working.

<
7条回答
  •  无人共我
    2021-01-31 21:23

    A version of the answer by boen_robot which avoids the overflow issue, using BC Math if available.

    function ipv62numeric($ip)
    {
        $str = '';
        foreach (unpack('C*', inet_pton($ip)) as $byte) {
            $str .= str_pad(decbin($byte), 8, '0', STR_PAD_LEFT);
        }
        $str = ltrim($str, '0');
        if (function_exists('bcadd')) {
            $numeric = 0;
            for ($i = 0; $i < strlen($str); $i++) {
                $right  = base_convert($str[$i], 2, 10);
                $numeric = bcadd(bcmul($numeric, 2), $right);
            }
            $str = $numeric;
        } else {
            $str = base_convert($str, 2, 10);
        }
    
        return $str;
    }
    

    Example:

    echo ipv62numeric('2001:11ff:ffff::f');
    

    Will return "42540853245347499564798372846648688655" as a string, which is the correct answer.

提交回复
热议问题