将数字还原为IPv6字符串表示形式 [英] Revert number to IPv6 string representation

查看:170
本文介绍了将数字还原为IPv6字符串表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用IP2Location数据库查找IPv6地址的国家/地区代码.它们具有方法,可将IPv6地址转换为可以使用的(大)数字查询他们的数据库.

I'm using the IP2Location database to find country codes for IPv6 addresses. They have a method to convert an IPv6 address to a (large) number which can be used to query their database.

$ipv6 = '2404:6800:4001:805::1006';
$int = inet_pton($ipv6);
$bits = 15;

$ipv6long = 0;

while($bits >= 0){
    $bin = sprintf("%08b", (ord($int[$bits])));

    if($ipv6long){
        $ipv6long = $bin . $ipv6long;
    }
    else{
        $ipv6long = $bin;
    }
    $bits--;
}
$ipv6long = gmp_strval(gmp_init($ipv6long, 2), 10);

在这种情况下,$ipv6long为4787508642609817793433434904901313196294.

In this case, $ipv6long would be 47875086426098177934326549022813196294.

现在我想知道这样的数字是否可以还原为地址的IPv6字符串表示形式.如果可以,怎么办?

Now Im wondering whether such a number can be reverted to the IPv6 string representation of the address. And if so, how?

推荐答案

可以格式化IPv6地址,但是您需要先转换为打包字符串(16个字符串,其中每个字符都是数字的一个字节).

inet_ntop() can format IPv6 addresses, but you need to convert to a packed string first (a 16 character string where each character is one byte of the number).

function ipv6number2string($number) {
    // convert to hex
    $hex = gmp_strval(gmp_init($number, 10), 16);
    // pad to 32 chars
    $hex = str_pad($hex, 32, '0', STR_PAD_LEFT);
    // convert to a binary string
    $packed = hex2bin($hex);
    // convert to IPv6 string
    return inet_ntop($packed);
}

echo ipv6number2string(47875086426098177934326549022813196294);

这篇关于将数字还原为IPv6字符串表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆