将IPv6地址转换为IP号的公式

时间:2016-07-11 15:35:13

标签: converter formula ipv6

我正在寻找将IPV6地址转换为IP号码的公式。这需要使用我们的geoip位置信息进行映射。

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

转换的输出IP号码:42540766411282592856904265327123268393

...谢谢

1 个答案:

答案 0 :(得分:2)

以下是多种语言的示例代码,用于将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.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