Skip to content

Instantly share code, notes, and snippets.

@deckerego
Last active May 25, 2021 02:13
Show Gist options
  • Save deckerego/0abc2ca6a33bc9d62e3caf6251296b10 to your computer and use it in GitHub Desktop.
Save deckerego/0abc2ca6a33bc9d62e3caf6251296b10 to your computer and use it in GitHub Desktop.
IPv4 Network Info Calculator & Iterator
function getIPv4Range(networkString) {
const networkdef = networkString.split('/');
const netmask = parseInt(networkdef[1])
const bitmask = 32 - netmask;
const quads = networkdef[0].split('.');
const addrbin =
(parseInt(quads[0]) << 24) +
(parseInt(quads[1]) << 16) +
(parseInt(quads[2]) << 8) +
parseInt(quads[3]);
const network = (addrbin >>> bitmask) << bitmask;
const wildcard = 0xFFFFFFFF >>> netmask;
const broadcast = network ^ wildcard;
return [network + 1, broadcast - 1];
}
function binToQuads(addrbits) {
const quadOne = addrbits >>> 24;
const quadTwo = (addrbits & 0x00FF0000) >> 16;
const quadThree = (addrbits & 0x0000FF00) >> 8;
const quadFour = addrbits & 0x000000FF;
return `${quadOne}.${quadTwo}.${quadThree}.${quadFour}`;
}
const [startAddr, endAddr] = getIPv4Range("127.0.0.1/29");
for(var addr = startAddr; addr <= endAddr; ++addr) {
console.log(binToQuads(addr));
}
function getNetworkInfo(networkString) {
const networkdef = networkString.split('/');
const netmask = parseInt(networkdef[1])
const bitmask = 32 - netmask;
const quads = networkdef[0].split('.');
const addrbin =
(parseInt(quads[0]) << 24) +
(parseInt(quads[1]) << 16) +
(parseInt(quads[2]) << 8) +
parseInt(quads[3]);
const network = (addrbin >>> bitmask) << bitmask;
const wildcard = 0xFFFFFFFF >>> netmask;
const broadcast = network ^ wildcard;
return {
network: `${binToQuads(network)}/${netmask}`,
wildcard: binToQuads(wildcard),
broadcast: binToQuads(broadcast),
firstAddress: binToQuads(network + 1),
lastAddress: binToQuads(broadcast - 1),
addressCount: broadcast - network - 1
};
}
function binToQuads(addrbits) {
const quadOne = addrbits >>> 24;
const quadTwo = (addrbits & 0x00FF0000) >> 16;
const quadThree = (addrbits & 0x0000FF00) >> 8;
const quadFour = addrbits & 0x000000FF;
return `${quadOne}.${quadTwo}.${quadThree}.${quadFour}`;
}
console.log(getNetworkInfo("127.0.0.1/19"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment