From 1327a476b9af3a0a845d8c7700ac1ae8a4c04ddd Mon Sep 17 00:00:00 2001 From: Michael Rowley Date: Thu, 30 Dec 2021 14:03:46 +0000 Subject: [PATCH] Added expandIpv6() --- src/core/lib/IP.mjs | 35 +++++++++++++++++++++++++++++++++-- src/core/operations/Sort.mjs | 1 - 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/core/lib/IP.mjs b/src/core/lib/IP.mjs index 7235d1fa..2e5a7870 100644 --- a/src/core/lib/IP.mjs +++ b/src/core/lib/IP.mjs @@ -351,8 +351,7 @@ export function ipv4ToStr(ipInt) { */ export function strToIpv6(ipStr, retArr=true) { if (retArr === false) { - // TODO: Expand address. - return Number("0x" + ipStr.replace(/:/g, "")); + return Number("0x" + expandIpv6(ipStr).replace(/:/g, "")); } let j = 0; 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. * diff --git a/src/core/operations/Sort.mjs b/src/core/operations/Sort.mjs index c3d75b32..80e09b95 100644 --- a/src/core/operations/Sort.mjs +++ b/src/core/operations/Sort.mjs @@ -117,7 +117,6 @@ class Sort extends Operation { static _ipv6Sort(a, b) { const ipLib = require("../lib/IP.mjs"); const numericalA = ipLib.strToIpv6(a, false), numericalB = ipLib.strToIpv6(b, false); - console.log(numericalA + " : " + numericalB); return numericalA - numericalB; }