Last active
February 2, 2021 14:38
-
-
Save encap/21cd7c7aa078de858cc7d10842cef969 to your computer and use it in GitHub Desktop.
Calculate network address from ip and mask (fragment of network_ip_tool in cidr repo)
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 [host, mask] = ev.target.value.split('/'); | |
if (host.split('.').length !== 4 || mask === undefined || !mask.length ||isNaN(mask)) { | |
console.warn('invalid input') | |
return; | |
} | |
const arrBinHost = host.split('.').map((octet) => { | |
const octetArr = Number(octet).toString(2).split(''); | |
const octetArrLength = octetArr.length | |
if (octetArrLength < 8) { | |
for (let i = 0; i < 8 - octetArrLength; i += 1) { | |
octetArr.unshift('0'); | |
} | |
}; | |
return octetArr; | |
}); | |
const binMask = Array(Number(mask) + 1).join('1') + Array(32 - Number(mask) + 1).join('0'); | |
const arrBinMask = binMask.match(/.{1,8}/g).map((octet) => octet.split('')); | |
const arrBinNet = arrBinMask | |
.map((octet, octetIndex) => { | |
return octet.map((digit, digitIndex) => | |
Number(digit) === 1 && Number(arrBinHost[octetIndex][digitIndex]) === 1 ? "1" : "0" | |
) | |
}) | |
const netIP = arrBinNet.map((octet) => parseInt(octet.join(''), 2)).join('.'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment