Created
December 17, 2019 18:56
-
-
Save andremarcondesteixeira/aebd73f556115d01c5ee30f3a2282cca to your computer and use it in GitHub Desktop.
This file contains hidden or 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
export function calculateIpv4Subnet(ipAddress, subnetMask) { | |
// helper functions | |
const numbersArrayFromString = v => v.split('.').map(v => parseInt(v)); | |
const numberBinaryAsString = v => (v >>> 0).toString(2).padStart(8, '0'); | |
const addressBinaryAsString = v => numbersArrayFromString(v).map(numberBinaryAsString).join(''); | |
const addressAsNumber = v => parseInt(addressBinaryAsString(v), 2); | |
const addressStringFromNumber = v => [24, 16, 8, 0].map(shift => (v >>> shift) & 255).join('.'); | |
ipAddressNumber = addressAsNumber(ipAddress); | |
subnetMaskNumber = addressAsNumber(subnetMask); | |
const networkAddress = ipAddressNumber & subnetMaskNumber; | |
const amountOfHostsPerSubnet = parseInt(addressBinaryAsString(subnetMask).replace(/^1*/, '1'), 2); | |
const broadcastAddress = networkAddress + amountOfHostsPerSubnet - 1; | |
const isCidr32 = subnetMask === '255.255.255.255'; | |
const firstUsableIpAddress = isCidr32 ? networkAddress : networkAddress + 1; | |
const lastUsableIpAddress = isCidr32 ? broadcastAddress : broadcastAddress - 1; | |
const cidr = addressBinaryAsString(subnetMask).replace(/0{1,}$/, '').split('').length; | |
const amountOfUsableIpAddresses = isCidr32 ? 0 : amountOfHostsPerSubnet - 2; | |
return { | |
ipAddress: ipAddress, | |
subnetMask: subnetMask, | |
networkAddress: addressStringFromNumber(networkAddress), | |
broadcastAddress: addressStringFromNumber(broadcastAddress), | |
amountOfIpAddresses: amountOfHostsPerSubnet, | |
amountOfUsableIpAddresses: amountOfUsableIpAddresses, | |
firstUsableIpAddress: amountOfUsableIpAddresses > 0 ? addressStringFromNumber(firstUsableIpAddress) : null, | |
lastUsableIpAddress: amountOfUsableIpAddresses > 0 ? addressStringFromNumber(lastUsableIpAddress) : null, | |
cidr: `/${cidr}`, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment