Php convert ipv6 to number

前端 未结 7 902
醉话见心
醉话见心 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:26

    Note that all answers will result in incorrect results for big IP addresses or are going through a highly complicated process to receive the actual numbers. Retrieving the actual integer value from an IPv6 address requires two things:

    1. IPv6 support
    2. GMP extension (--with-gmp)

    With both prerequisites in place conversion is as simple as:

    $ip = 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff';
    $int = gmp_import(inet_pton($ip));
    
    echo $int; // 340282366920938463463374607431768211455
    

    The binary numeric packed in_addr representation that is returned by inet_pton is already an integer and can directly be imported to GMP, as illustrated above. There is no need for special conversions or anything.

    Note that the other way around is equally simple:

    $int = '340282366920938463463374607431768211455';
    $ip = inet_ntop(str_pad(gmp_export($int), 16, "\0", STR_PAD_LEFT));
    
    echo $ip; // ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
    

    Hence building the two desired functions is as simple as:

    function ipv6_to_integer($ip) {
        return (string) gmp_import(inet_pton($ip));
    }
    
    function ipv6_from_integer($integer) {
        return inet_ntop(str_pad(gmp_export($integer), 16, "\0", STR_PAD_LEFT));
    }
    

提交回复
热议问题