IPv4 CIDR Calculator CLI
A Node CLI that parses an IPv4 CIDR block and prints the network address, broadcast address, netmask, and the range of usable host addresses.
Project
node-ip-cidr-calc
Entry point: cidr.mjs
Install
node --versionRun
node cidr.mjs 192.168.1.10/24Test
node --test cidr.test.mjsExpected output
Prints the network, broadcast, netmask, and host range for the given CIDR block.Dependencies
- node >=20
What it does
Computes the addresses that matter inside an IPv4 CIDR block using integer math on the 32-bit address value.
function parseCidr(input) {
const [ip, prefixRaw] = input.split('/');
const prefix = Number(prefixRaw);
const parts = ip.split('.').map(Number);
if (parts.length !== 4 || parts.some((n) => n < 0 || n > 255) || !Number.isInteger(prefix) || prefix < 0 || prefix > 32) {
throw new Error('invalid cidr: ' + input);
}
const value = ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
return { value, prefix };
}
function toIp(value) {
return [24, 16, 8, 0].map((shift) => (value >>> shift) & 255).join('.');
}
const { value, prefix } = parseCidr(process.argv[2] ?? '');
const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
const network = (value & mask) >>> 0;
const broadcast = (network | (~mask >>> 0)) >>> 0;
const hosts = Math.max(0, broadcast - network - 1);
console.log('network ' + toIp(network));
console.log('broadcast ' + toIp(broadcast));
console.log('netmask ' + toIp(mask));
console.log('hosts ' + (hosts ? toIp(network + 1) + ' - ' + toIp(broadcast - 1) : 'none'));
It rejects prefixes outside 0 to 32 and reports a /31 and /32 as having no usable host range, which matches how those blocks actually behave.
Run and verify
node cidr.mjs 192.168.1.10/24
Run with any host address inside a block; the calculator normalises it to the containing network.
Expected Output
For 192.168.1.10/24 the program should print the network, broadcast, netmask, and host range. The output is:
network 192.168.1.0
broadcast 192.168.1.255
netmask 255.255.255.0
hosts 192.168.1.1 - 192.168.1.254
A /31 or /32 block prints none as the host range, and an invalid prefix exits with an error instead of computing garbage.
Limitations
IPv4 only; IPv6 needs 128-bit handling. Usable-host rules for /31 and /32 follow the common convention and may differ from some vendor documentation.