Added expandIpv6()

This commit is contained in:
Michael Rowley 2021-12-30 14:03:46 +00:00
parent 1eb6d03a6f
commit 1327a476b9
2 changed files with 33 additions and 3 deletions

View file

@ -351,8 +351,7 @@ export function ipv4ToStr(ipInt) {
*/ */
export function strToIpv6(ipStr, retArr=true) { export function strToIpv6(ipStr, retArr=true) {
if (retArr === false) { if (retArr === false) {
// TODO: Expand address. return Number("0x" + expandIpv6(ipStr).replace(/:/g, ""));
return Number("0x" + ipStr.replace(/:/g, ""));
} }
let j = 0; let j = 0;
const blocks = ipStr.split(":"), const blocks = ipStr.split(":"),
@ -386,6 +385,38 @@ export function strToIpv6(ipStr, retArr=true) {
} }
} }
/**
* Expands an IPv6 address in string format to its 'longhand' equivalent.
*
* @param {string} ipStr
* @returns {string}
*
* @example
* // returns "5555:126f:0000:0000:0000:0000:0000:0001"
* expandIpv6("5555:126f::0001");
*/
export function expandIpv6(ipStr) {
const compactIndex = ipStr.search("::");
if (compactIndex === -1) {
// There were no occurances of '::'
// in ipStr.
return ipStr;
}
let expandedStr = ipStr.substring(0, compactIndex); // 1234:5678::..
const insertOffset = compactIndex == 0 ? 1 : 0;
const ipEnd = ipStr.substring(compactIndex + 1);
const missingChars = 39 - (expandedStr.length + ipEnd.length);
for (let i = insertOffset; i < missingChars + insertOffset; i++) {
if (i % 5 == 0) {
expandedStr += ":";
continue;
}
expandedStr += "0";
}
expandedStr += ipEnd;
return expandedStr;
}
/** /**
* Converts an IPv6 address from numerical array format to string format. * Converts an IPv6 address from numerical array format to string format.
* *

View file

@ -117,7 +117,6 @@ class Sort extends Operation {
static _ipv6Sort(a, b) { static _ipv6Sort(a, b) {
const ipLib = require("../lib/IP.mjs"); const ipLib = require("../lib/IP.mjs");
const numericalA = ipLib.strToIpv6(a, false), numericalB = ipLib.strToIpv6(b, false); const numericalA = ipLib.strToIpv6(a, false), numericalB = ipLib.strToIpv6(b, false);
console.log(numericalA + " : " + numericalB);
return numericalA - numericalB; return numericalA - numericalB;
} }