Calculate IPv4 prefix ranges
Turn a CIDR prefix into inclusive address boundaries without enumerating every address.
Prefix length describes a block
An IPv4 prefix length says how many of the 32 address bits identify the network. Its block contains 2 raised to the power of 32 minus the prefix length addresses. Divide the address number by that block size, take the integer part and multiply back to obtain the network boundary.
For this exercise, a valid address with host bits set is normalised to its network. An address ending in .9 with /24 therefore belongs to the same block as the corresponding .0/24. The last address is the first plus the block size minus one. No loop over every address is needed, even for /0.
Count addresses, not assumed usable hosts
A /31 contains two addresses and /32 contains one. Do not blindly subtract two: address use depends on context, and this report describes inclusive ranges rather than a host-allocation policy. A /0 covers the entire IPv4 number space.
The supplied lib/ipv4.awk is trusted course code. Its cidr function returns success or failure and exposes first, last, block and prefix only on success. Its dotted function formats a numeric address. Read the helper before using it; later scripts depend on this small, explicit contract rather than device-specific subnet commands. See the CIDR specification for prefix notation.
awk -f lib/ipv4.awk -f - <<'AWK'
BEGIN {if(cidr("192.0.2.9/24"))print dotted(first),dotted(last)}
AWK
Put it into practice.
Read prefixes.txt, one CIDR candidate per line. Print cidr<TAB>network<TAB>last<TAB>addresses<TAB>state in input order. Accept a canonical IPv4 address followed by / and a canonical decimal prefix 0–32. Normalise host bits to the network boundary. Valid rows show dotted first/last, the full block address count and valid. Invalid rows show - for all three values and invalid. The supplied lib/ipv4.awk exports ipv4(), dotted(), and cidr(); successful cidr() sets first, last, block and prefix.
See an explained solution
export LC_ALL=C
printf 'cidr\tnetwork\tlast\taddresses\tstate\n'
awk -f lib/ipv4.awk -f - prefixes.txt <<'AWK'
{if(cidr($0))printf "%s\t%s\t%s\t%.0f\tvalid\n",$0,dotted(first),dotted(last),block
else printf "%s\t-\t-\t-\tinvalid\n",$0}
AWK
The helper validates the entire candidate before computing bounds. Using a block formula handles small and enormous prefixes uniformly, while reporting address count avoids making an unsupported usable-host assumption.