Skip to content

Instantly share code, notes, and snippets.

@vlas-ilya
Created June 29, 2020 17:26
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 vlas-ilya/6e11187f9c0b062a1f742700d5d1bc51 to your computer and use it in GitHub Desktop.
Save vlas-ilya/6e11187f9c0b062a1f742700d5d1bc51 to your computer and use it in GitHub Desktop.
Get ips by mask
const int2ip = (ipInt) => (
(ipInt >>> 24) + '.' +
(ipInt >> 16 & 255) + '.' +
(ipInt >> 8 & 255) + '.' +
(ipInt & 255)
);
const ip2int = (ip) => ip.split('.').reduce(
(ipInt, octet) => (ipInt << 8) + parseInt(octet, 10), 0
) >>> 0;
const toIntMask = (mask) => parseInt([
...[...Array(+mask)].map(_ => 1),
...[...Array(32 - mask)].map(_ => 0)
].join(''), 2);
const invertMask = (mask) => parseInt([...Array(32 - mask)]
.map(_ => 1)
.join(''), 2);
const getIpInterval = (ip, mask) => {
const intIp = ip2int(ip);
const intMask = toIntMask(mask);
const intInvertedMask = invertMask(mask);
const minIp = (intIp & intMask);
const maxIp = (intIp | intInvertedMask);
return [minIp, maxIp];
}
function getIps(ipString) {
const [ip, mask] = ipString.split("/");
const [minIp, maxIp] = getIpInterval(ip, mask);
for (let i = minIp; i <= maxIp; i++) {
console.log(int2ip(i));
}
}
getIps("91.221.31.77/24");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment