beaugunderson / ip-address

💻 a library for parsing and manipulating IPv4 and IPv6 addresses in JavaScript
http://ip-address.js.org/
MIT License
580 stars 73 forks source link

cidr valid checks? #75

Closed lvdang closed 6 years ago

lvdang commented 6 years ago

How do I check for valid cidr? I think I figured it out.

const ipp = "192.168.0.0".split('.'); const num = 16; const networkMask = createNetmaskAddr(num).split('.'); const isCIDR = checkCIDR(networkMask, ipp);

// wrote this method to compare the netmask with the ip. function checkCIDR(netmask, ip) { if (ip.length !== netmask.length) { return false; }

let i = 0; const len = ip.length;

while(i < len) { const max = Number(netmask[i]); if (max !== 255 && max !== Number(ip[i])) { return false; } i++; }

return true; }

// credit to: https://stackoverflow.com/questions/21903482/cidr-to-netmask-conversion-in-javascript function createNetmaskAddr(bitCount) { var mask=[]; for(i=0;i<4;i++) { var n = Math.min(bitCount, 8); mask.push(256 - Math.pow(2, 8-n)); bitCount -= n; } return mask.join('.'); }