Created
June 29, 2020 17:26
-
-
Save vlas-ilya/6e11187f9c0b062a1f742700d5d1bc51 to your computer and use it in GitHub Desktop.
Get ips by mask
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 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