Skip to content

Instantly share code, notes, and snippets.

@KaKi87
Created February 20, 2020 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KaKi87/7c3907a1ec03ebc8ecb0294ab7176bce to your computer and use it in GitHub Desktop.
Save KaKi87/7c3907a1ec03ebc8ecb0294ab7176bce to your computer and use it in GitHub Desktop.
Is IP in CIDR ?
const isIpInCidr = (ip, cidr) => {
const [range, bits = 32] = cidr.split('/');
const mask = ~(2 ** (32 - bits) - 1);
const ip4ToInt = ip => ip.split('.').reduce((int, oct) => (int << 8) + parseInt(oct, 10), 0) >>> 0;
return (ip4ToInt(ip) & mask) === (ip4ToInt(range) & mask);
};
/*
Source : https://tech.mybuilder.com/determining-if-an-ipv4-address-is-within-a-cidr-range-in-javascript/
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment