Converting a simplified IPv6 address format back to the full format is a straightforward task. There are specific rules that govern how addresses can be simplified, and following these rules in reverse order will help you convert the address successfully:
The presence of a Dotted-quad notation (IPv4 address embedded inside IPv6 address)
Omitting leading zeros
Abbreviating groups of zeros with ::
In some cases, depending on your processing method, rule 2 and 3 might need to be interchanged.
Here's a basic converter designed to handle valid IPv6 addresses only (it won't work for invalid ones as no validation is performed):
function full_IPv6 (ip_string) {
// replacing any embedded ipv4 address
var ipv4 = ip_string.match(/(.*:)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$)/);
if (ipv4) {
var ip_string = ipv4[1];
ipv4 = ipv4[2].match(/[0-9]+/g);
for (var i = 0;i < 4;i ++) {
var byte = parseInt(ipv4[i],10);
ipv4[i] = ("0" + byte.toString(16)).substr(-2);
}
ip_string += ipv4[0] + ipv4[1] + ':' + ipv4[2] + ipv4[3];
}
// handling leading and trailing ::
ip_string = ip_string.replace(/^:|:$/g, '');
var ipv6 = ip_string.split(':');
for (var i = 0; i < ipv6.length; i ++) {
var hex = ipv6[i];
if (hex != "") {
// normalizing leading zeros
ipv6[i] = ("0000" + hex).substr(-4);
}
else {
// normalizing grouped zeros ::
hex = [];
for (var j = ipv6.length; j <= 8; j ++) {
hex.push('0000');
}
ipv6[i] = hex.join(':');
}
}
return ipv6.join(':');
}
You could perform the embedded IPv4 processing after the .split(':')
, but the code above uses regex for that purpose. Each step of the conversion process outlined here is quite simple. The only issue I faced was an off-by-one error in the j<=8
condition within the final for loop.