How can I convert IPV6 address to IPV4 address?

176,873

Solution 1

While there are IPv6 equivalents for the IPv4 address range, you can't convert all IPv6 addresses to IPv4 - there are more IPv6 addresses than there are IPv4 addresses.

The only sane way around this issue is to update your application to be able to understand and store IPv6 addresses.

Solution 2

The IPAddress Java library can accomplish what you are describing here.

IPv6 addresses are 16 bytes. Using that library, if you are starting with a 16-byte array you can construct the IPv6 address object:

IPv6Address addr = new IPv6Address(bytes); //bytes is byte[16]

From there you can check if the address is IPv4 mapped, IPv4 compatible, IPv4 translated, and so on (there are many possible ways IPv6 represents IPv4 addresses). In most cases, if an IPv6 address represents an IPv4 address, the ipv4 address is in the lower 4 bytes, and so you can get the derived IPv4 address as follows. Afterwards, you can convert back to bytes, which will be just 4 bytes for IPv4.

    if(addr.isIPv4Compatible() || addr.isIPv4Mapped()) {
        IPv4Address derivedIpv4Address = addr.getEmbeddedIPv4Address();
        byte ipv4Bytes[] = derivedIpv4Address.getBytes();
        ...
     }

The javadoc is available at the link.

Solution 3

Here is the code you are looking for in javascript. Well you know you can't convert all of the ipv6 addresses

<script>
function parseIp6(str)
{
  //init
  var ar=new Array;
  for(var i=0;i<8;i++)ar[i]=0;
  //check for trivial IPs
  if(str=="::")return ar;
  //parse
  var sar=str.split(':');
  var slen=sar.length;
  if(slen>8)slen=8;
  var j=0;
  for(var i=0;i<slen;i++){
    //this is a "::", switch to end-run mode
    if(i && sar[i]==""){j=9-slen+i;continue;}
    ar[j]=parseInt("0x0"+sar[i]);
    j++;
  }

  return ar;
}
function ipcnvfrom6(ip6)
{
  var ip6=parseIp6(ip6);
  var ip4=(ip6[6]>>8)+"."+(ip6[6]&0xff)+"."+(ip6[7]>>8)+"."+(ip6[7]&0xff);
  return ip4;
}
alert(ipcnvfrom6("::C0A8:4A07"));
</script>

Solution 4

There isn't a 1-1 correspondence between IPv4 and IPv6 addresses (nor between IP addresses and devices), so what you're asking for generally isn't possible.

There is a particular range of IPv6 addresses that actually represent the IPv4 address space, but general IPv6 addresses will not be from this range.

Solution 5

Vishnuraj V's post solved my issue as well. Thanks for that!

I converted the functions into one function and fixed a few minor bugs: JSFiddle

HTML:

<div id="ipAddress">

</div>

JS:

/* Convert IPv6 address to IPv4 address */
/* Fork from: https://stackoverflow.com/a/23147817/11404332 */
function IP6to4(ip6) {
    function parseIp6(ip6str) {
        const str = ip6str.toString();

        // Initialize
        const ar = new Array();
        for (var i = 0; i < 8; i++) ar[i] = 0;

        // Check for trivial IPs
        if (str == '::') return ar;
        
        // Parse
        const sar = str.split(':');
        let slen = sar.length;
        if (slen > 8) slen = 8;
        let j = 0;
        i = 0
        for (i = 0; i < slen; i++) {
            // This is a "::", switch to end-run mode
            if (i && sar[i] == '') {
                j = 9 - slen + i;
                continue;
            }
            ar[j] = parseInt(`0x0${sar[i]}`);
            j++;
        }

        return ar;
    }

    var ip6parsed = parseIp6(ip6);
    const ip4 = `${ip6parsed[6] >> 8}.${ip6parsed[6] & 0xff}.${ip6parsed[7] >> 8}.${ip6parsed[7] & 0xff}`;
    return ip4;
}

/* Usage */
const ipAddress = '0:0:0:0:0:FFFF:7F00:0001';
document.getElementById("ipAddress").innerText = IP6to4(ipAddress);
Share:
176,873
newbie
Author by

newbie

Java developer

Updated on August 26, 2021

Comments

  • newbie
    newbie over 2 years

    I have application that uses IPv4 addresses (it stores them as long), so it only understands IPv4 addresses.

    Is it possible to convert IPv6 address to IPv4 with Java?

  • newbie
    newbie about 14 years
    I know that, but currently most of addresses are inside IPV4 space. I just need to method to convert those addresses that exist in IPV4 space.
  • zelibobla
    zelibobla over 7 years
    Please, update your answer providing the way to convert before your caution about IPv6 tp IPv4 compatibility.
  • Magno C
    Magno C over 5 years
    Shouldn't ipv6Address be addr ? .. and ipv4Address be derivedIpv4Address ? Please show us a concise code. The code is not working anyway: getLowerIPv4Address is undefined.
  • Sean F
    Sean F over 5 years
    @MagnoC You are correct, getLowerIPv4Address was the name of the method in an earlier version of the library, the name is now getEmbeddedIPv4Address. Also, you're right about the mismatched var names, I've updated the code example.