From d507258ef2b2eeddbccd9660305136291c65d4bf Mon Sep 17 00:00:00 2001 From: Matthias Hannig Date: Sun, 9 Sep 2018 18:35:27 +0200 Subject: [PATCH] added ip parser helper --- client/components/utils/ip.jsx | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 client/components/utils/ip.jsx diff --git a/client/components/utils/ip.jsx b/client/components/utils/ip.jsx new file mode 100644 index 0000000..80bb113 --- /dev/null +++ b/client/components/utils/ip.jsx @@ -0,0 +1,35 @@ + +import bigInt from 'big-integer' + + +export function IPv6ToNumeric(addr) { + const parts = addr.split(":"); // let's se what we can do about the :: expansion + let expanded = []; + + for (let p of parts) { + let binary = parseInt(p, 16).toString(2); // Convert to binary + while (binary.length < 16) { + // Leftpad + binary = "0" + binary; + } + expanded.push(binary); + } + + return bigInt(expanded.join(""), 2); +} + +export function IPv4ToNumeric(addr) { + const octets = addr.split('.'); + return parseInt(octets[0], 10) * 16777216 + // 256^3 + parseInt(octets[1], 10) * 65536 + // 256^2 + parseInt(octets[2], 10) * 256 + // 256^1 + parseInt(octets[3], 10); // 256^0 +} + +export function ipToNumeric(addr) { + if (addr.includes(":")) { + return IPv6ToNumeric(addr); + } + return IPv4ToNumeric(addr); +} +