How can I convert IPV6 address to IPV4 address?
Asked Answered
M

6

17

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?

Maniac answered 7/5, 2010 at 6:29 Comment(2)
There are 79,228,162,514,264,337,593,543,950,336 times the number of possible IPv4 addresses for IPv6 addresses. (2^32 IPv4 addresses and 2^128 IPv6 addresses, so there are 2^96 times the number of IPv4 addresses for IPv6 than for IPv4.)Regolith
@gotqn "IPv4", "IPv6" and "Java" aren't code, so please don't format them as code. See Should I use code blocks when mentioning framework names/technologies? and Inline Code Spans should not be used for emphasis, right?Meemeece
T
24

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.

Threnode answered 7/5, 2010 at 6:33 Comment(2)
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.Maniac
Please, update your answer providing the way to convert before your caution about IPv6 tp IPv4 compatibility.Ozuna
C
10

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.

Cumulation answered 7/9, 2016 at 13:46 Comment(2)
Shouldn't ipv6Address be addr ? .. and ipv4Address be derivedIpv4Address ? Please show us a concise code. The code is not working anyway: getLowerIPv4Address is undefined.Synergism
@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.Cumulation
P
8

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.

Porphyria answered 7/5, 2010 at 6:32 Comment(0)
P
7

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>
Pardo answered 18/4, 2014 at 5:14 Comment(0)
L
1

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://mcmap.net/q/688467/-how-can-i-convert-ipv6-address-to-ipv4-address */
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);
Luxate answered 31/7, 2021 at 17:11 Comment(0)
L
0

I'm the author of https://ipxplorer.com/tools/convert-ipv6-to-ipv4, an online IPv6 to IPv4 address converter.

Here is how the converter does the conversion

public String convertIpv6To4(String ipv6) throws UnknownHostException, RuntimeException{
    try {
        InetAddress inetAddress = InetAddress.getByName(ipv6);
        if (inetAddress instanceof Inet6Address) {
            byte[] ipv6Bytes = inetAddress.getAddress();
            byte[] ipv4Bytes = new byte[4];
            System.arraycopy(ipv6Bytes, 12, ipv4Bytes, 0, 4);
            InetAddress ipv4Address = InetAddress.getByAddress(ipv4Bytes);
            return (ipv4Address.getHostAddress());
        } else {
            throw new RuntimeException("Not an IPv6 address.");
        }
    } catch (UnknownHostException e) {
        throw new UnknownHostException("Invalid IPv6 address");
    }
}
Lonnie answered 18/11, 2023 at 9:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.