3

I'm looking for a formula to convert IPV6 address to IP number. This is required to map with geoip location information we have.

Input IPV6 address : 2001:0db8:0000:0000:0000:ff00:0042:8329

Output IP Number converted : 42540766411282592856904265327123268393

Thanks...

Hamid Rouhani
  • 2,309
  • 2
  • 31
  • 45
user5758169
  • 31
  • 1
  • 2

1 Answers1

6

Below are the sample codes in multiple languages to convert IPv6 address to number taken from 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
Michael C.
  • 1,410
  • 1
  • 9
  • 20