Created
June 20, 2018 22:55
-
-
Save rg443a/2d8d8afb6922bae7a70fed3870a7c8a2 to your computer and use it in GitHub Desktop.
ip4ToInt, intToIp4, intToBin, isIp4InCidr, calculateCidrRange
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ip4ToInt = ip => | |
ip.split('.').reduce((int, oct) => (int << 8) + parseInt(oct, 10), 0) >>> 0; | |
const isIp4InCidr = ip => cidr => { | |
const [range, bits = 32] = cidr.split('/'); | |
const mask = ~(2 ** (32 - bits) - 1); | |
return (ip4ToInt(ip) & mask) === (ip4ToInt(range) & mask); | |
}; | |
const isIp4InCidrs = (ip, cidrs) => cidrs.some(isIp4InCidr(ip)); | |
// isIp4InCidrs('192.168.1.5', ['10.10.0.0/16', '192.168.1.1/24']); // true | |
const intToIp4 = int => | |
[(int >>> 24) & 0xFF, (int >>> 16) & 0xFF, | |
(int >>> 8) & 0xFF, int & 0xFF].join('.'); | |
const calculateCidrRange = cidr => { | |
const [range, bits = 32] = cidr.split('/'); | |
const mask = ~(2 ** (32 - bits) - 1); | |
return [intToIp4(ip4ToInt(range) & mask), intToIp4(ip4ToInt(range) | ~mask)]; | |
}; | |
calculateCidrRange('192.168.1.0/24'); // ["192.168.1.0", "192.168.1.255"] | |
const intToBin = int => | |
(int >>> 0).toString(2).padStart(32, 0).match(/.{1,8}/g).join('.'); | |
intToBin(ip4ToInt('192.168.1.1')); // 11000000.10101000.00000001.00000001 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment