【问题标题】:Formula to convert IPv6 Address to IP number将 IPv6 地址转换为 IP 号的公式
【发布时间】:2016-11-13 15:12:37
【问题描述】:

我正在寻找将IPV6 地址转换为IP 数字的公式。这是映射我们拥有的 geoip 位置信息所必需的。

输入IPV6地址:2001:0db8:0000:0000:0000:ff00:0042:8329

转换后的输出IP:42540766411282592856904265327123268393

谢谢...

【问题讨论】:

标签: converter formula ipv6


【解决方案1】:

以下是多语言的示例代码,用于将 IPv6 地址转换为取自 http://lite.ip2location.com/faqs 的数字

PHP

$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);

Java

java.math.BigInteger Dot2LongIP(String ipv6) {
    java.net.InetAddress ia = java.net.InetAddress.getByName(ipv6);
    byte byteArr[] = ia.getAddress();

    if (ia instanceof java.net.Inet6Address) {
        java.math.BigInteger ipnumber = new java.math.BigInteger(1, byteArr);
        return ipnumber;
    }
}

C#

string strIP = "2404:6800:4001:805::1006";
System.Net.IPAddress address;
System.Numerics.BigInteger ipnum;

if (System.Net.IPAddress.TryParse(strIP, out address)) {
    byte[] addrBytes = address.GetAddressBytes();

    if (System.BitConverter.IsLittleEndian) {
        System.Collections.Generic.List byteList = new System.Collections.Generic.List(addrBytes);
        byteList.Reverse();
        addrBytes = byteList.ToArray();
    }

    if (addrBytes.Length > 8) {
        //IPv6
        ipnum = System.BitConverter.ToUInt64(addrBytes, 8);
        ipnum <<= 64;
        ipnum += System.BitConverter.ToUInt64(addrBytes, 0);
    } else {
        //IPv4
        ipnum = System.BitConverter.ToUInt32(addrBytes, 0);
    }
}

VB.NET

Dim strIP As String = "2404:6800:4001:805::1006"
Dim address As System.Net.IPAddress
Dim ipnum As System.Numerics.BigInteger

If System.Net.IPAddress.TryParse(strIP, address) Then
    Dim addrBytes() As Byte = address.GetAddressBytes()

    If System.BitConverter.IsLittleEndian Then
        Dim byteList As New System.Collections.Generic.List(Of Byte)(addrBytes)
        byteList.Reverse()
        addrBytes = byteList.ToArray()
    End If

    If addrBytes.Length > 8 Then
        'IPv6
        ipnum = System.BitConverter.ToUInt64(addrBytes, 8)
        ipnum <<= 64
        ipnum += System.BitConverter.ToUInt64(addrBytes, 0)
    Else
        'IPv4
        ipnum = System.BitConverter.ToUInt32(addrBytes, 0)
    End If
End If

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多