How to convert an address from IPv4 to IPv6

Viewed 60348

Is this possible? How can you convert an ipv4 to an ipv6 address?

a few example from here:

0.0.0.0   -> ::
127.0.0.1 -> ::1

I'm searching a solution in Java.

Thanks,

6 Answers

Here is the conversion code in Javascript

/** IPV4 CIDR to IPV6 CIDR conversion **/
function covertIPv6(x){
let ipV4 = x;
let address = ipV4.split('/');
let classValues = [];

if(address.length){
  classValues = address[0].split('.');
}
if(classValues.length){  
  let str = classValues.reduce((acc, val, ind)=>{
    let mod = +val >= 16 ? +val%16 : +val;
    let divider = +val >= 16 ? (val-mod)/16 : 0;
    const hexaCode = (hexaVal)=>{
      switch(hexaVal){
      case 10:
        hexaVal = 'A';
        break;
      case 11:
        hexaVal = 'B';
        break;
      case 12:
        hexaVal = 'C';
        break;
      case 13:
        hexaVal = 'D';
        break;
      case 14:
        hexaVal = 'E';
        break;
      case 15:
        hexaVal = 'F';
        break;
      default:
        hexaVal = hexaVal;
        break;
    }
      return hexaVal;
    }
    mod = hexaCode(mod);
    divider = hexaCode(divider);
    return ind === 1 ? `${acc}${divider}${mod}:`:`${acc}${divider}${mod}`
  },'')
  return `2002:${str}::/${address[1]}`;
}
  return "Invalid Address";
}

// Run the function

console.log(covertIPv6("0.0.0.0/12"));

Related