-
Notifications
You must be signed in to change notification settings - Fork 83
/
cidr.js
66 lines (59 loc) · 1.42 KB
/
cidr.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
61
62
63
64
65
66
/**
* CIDR checker
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This file controls support for checking to see if an IP matches a
* CIDR range.
*
* @license MIT license
*/
'use strict';
let ipToLong = exports.ipToLong = function (ip) {
let numIp = 0;
let parts = ip.split('.');
for (let i = 0, len = parts.length; i < len; i++) {
numIp *= 256;
numIp += Number(parts[i]);
}
return numIp;
};
let getPattern = exports.getPattern = function (cidr) {
if (!cidr) return null;
let index = cidr.indexOf('/');
if (index > 0) {
let subnet = ipToLong(cidr.substr(0, index));
let bits = parseInt(cidr.substr(index + 1));
let mask = -1 << (32 - bits);
return [subnet & mask, mask];
}
return [ipToLong(cidr), -1];
};
/**
* Returns a checker function for the passed CIDR range or array of
* ranges. The checker function returns boolean whether or not its
* passed IP is in the range.
*/
let checker = exports.checker = function (cidr) {
if (!cidr || !cidr.length) {
return () => false;
}
let patterns;
if (Array.isArray(cidr)) {
patterns = cidr.map(getPattern).filter(x => x);
} else {
patterns = [getPattern(cidr)];
}
return ip => {
let longip = ipToLong(ip);
for (let i = 0; i < patterns.length; ++i) {
let pattern = patterns[i];
if ((longip & pattern[1]) === pattern[0]) {
return true;
}
}
return false;
};
};
exports.check = function (cidr, ip) {
return checker(cidr)(ip);
};