forked from danielcompton/ip-range-check
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (51 loc) · 1.63 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Copyright (C) 2023 by Videsk - All Rights Reserved
* @name LIBRARY_NAME
* @author Daniel Compton (http://danielcompton.net)
* @license MIT
* Written by Daniel Compton (http://danielcompton.net), maintained by Videsk (https://github.com/videsk)
*
* Check whether an IP(v4 or v6) is in an CIDR range
*
*/
const ipaddr = require("ipaddr.js");
/**
* Verify CIDR IP list
* @param ipAddress {String} IP address
* @param ipList {String|[String]} IPs to compare
* @returns {*|boolean|boolean}
*/
function verifyCIDRList(ipAddress = '', ipList = '') {
if (!Array.isArray(ipList)) return verifyCIDR(ipAddress, ipList);
let isValid = false;
for (let i = 0; i < ipList.length; i++) {
if (verifyCIDR(ipAddress, ipList[i])) {
isValid = true;
break;
}
}
return isValid;
}
/**
* Compare individual IP
* @param ipAddress {String} IP address
* @param cidr {String} IP to compare
* @returns {boolean}
*/
function verifyCIDR(ipAddress = '', cidr = '') {
try {
const parsedIpAddress = ipaddr.parse(ipAddress);
if (cidr.includes('/')) {
const ip = ipaddr.parseCIDR(cidr);
return parsedIpAddress.match(ip);
}
const cidrAsIp = ipaddr.parse(cidr);
if ((parsedIpAddress.kind() === 'ipv6') && (cidrAsIp.kind() === 'ipv6')) return parsedIpAddress.toNormalizedString() === cidrAsIp.toNormalizedString();
return parsedIpAddress.toString() === cidrAsIp.toString();
}
catch (error) {
if (process.env.NODE_ENV !== 'production') console.error(error);
return false;
}
}
module.exports = verifyCIDRList;