1
0
mirror of https://github.com/nttgin/BGPalerter.git synced 2024-05-19 06:50:08 +00:00
Files
nttgin-BGPalerter/ipUtils.js

85 lines
2.3 KiB
JavaScript
Raw Normal View History

2019-08-15 18:02:17 +02:00
import { Address4, Address6 } from "ip-address";
const ip = {
2019-08-15 19:31:11 +02:00
isValidPrefix: function(prefix){
let bits, ip;
try {
if (prefix.indexOf("/") !== -1) {
const components = prefix.split("/");
ip = components[0];
bits = parseInt(components[1]);
} else {
return false;
}
if (ip.indexOf(":") === -1) {
return this.isValidIP(ip) && (bits >= 0 && bits <= 32);
} else {
return this.isValidIP(ip) && (bits >= 0 && bits <= 128);
}
} catch (e) {
return false;
2019-08-15 18:02:17 +02:00
}
2019-08-15 19:31:11 +02:00
},
isValidIP: function(ip) {
2019-08-15 18:02:17 +02:00
2019-08-15 19:31:11 +02:00
try {
if (ip.indexOf(":") === -1) {
return new Address4(ip).isValid();
} else {
return new Address6(ip).isValid();
}
} catch (e) {
return false;
2019-08-15 18:02:17 +02:00
}
},
2019-06-28 03:46:48 +02:00
sortByPrefixLength: function (a, b) {
2019-07-09 02:46:08 +02:00
const netA = a.split("/")[1];
const netB = b.split("/")[1];
return parseInt(netA) - parseInt(netB);
},
toDecimal: function(ip) {
let bytes = "";
if (ip.indexOf(":") == -1) {
bytes = ip.split(".").map(ip => parseInt(ip).toString(2).padStart(8, '0')).join("");
} else {
bytes = ip.split(":").filter(ip => ip !== "").map(ip => parseInt(ip, 16).toString(2).padStart(16, '0')).join("");
}
return bytes;
},
getNetmask: function(prefix) {
const components = prefix.split("/");
const ip = components[0];
const bits = components[1];
let binaryRoot;
if (ip.indexOf(":") == -1){
binaryRoot = this.toDecimal(ip).padEnd(32, '0').slice(0, bits);
} else {
binaryRoot = this.toDecimal(ip).padEnd(128, '0').slice(0, bits);
}
return binaryRoot;
},
isSubnet: function (prefixContainer, prefixContained) {
prefixContained = this.getNetmask(prefixContained);
prefixContainer = this.getNetmask(prefixContainer);
return prefixContained != prefixContainer && prefixContained.includes(prefixContainer);
2019-07-09 02:46:08 +02:00
}
2019-06-28 03:46:48 +02:00
};
module.exports = ip;