function cidrv4UsableSize
cidrv4UsableSize(cidr: Cidrv4): number

Returns the number of assignable addresses in a CIDR block.

This is cidrv4Size minus the network and broadcast addresses, except at /31 and /32 where the whole block is assignable — see cidrv4FirstUsableAddress. Writing cidrv4Size(cidr) - 2 by hand gets 0 for a /31 and -1 for a /32, which is why this is a function rather than a note in the docs.

The result is never zero: every IPv4 block has at least one assignable address.

Examples

Usable size from a Cidrv4 object

import { assertEquals } from "@std/assert";
import { cidrv4UsableSize, parseCidrv4 } from "@hertzg/ip/cidrv4";

assertEquals(cidrv4UsableSize(parseCidrv4("192.168.1.0/24")), 254);
assertEquals(cidrv4UsableSize(parseCidrv4("10.0.0.0/30")), 2);
assertEquals(cidrv4UsableSize(parseCidrv4("10.0.0.0/31")), 2);
assertEquals(cidrv4UsableSize(parseCidrv4("10.0.0.1/32")), 1);

Parameters

cidr: Cidrv4

The CIDR block

Return Type

number

The number of assignable addresses

cidrv4UsableSize(prefixLength: PrefixLengthv4): number

Returns the number of assignable addresses for a given prefix length.

Examples

Usable size from a prefix length

import { assertEquals } from "@std/assert";
import { cidrv4UsableSize } from "@hertzg/ip/cidrv4";

assertEquals(cidrv4UsableSize(24), 254);
assertEquals(cidrv4UsableSize(31), 2);
assertEquals(cidrv4UsableSize(32), 1);
assertEquals(cidrv4UsableSize(0), 4294967294);

Out-of-range prefix length throws

import { assertThrows } from "@std/assert";
import { cidrv4UsableSize } from "@hertzg/ip/cidrv4";

assertThrows(() => cidrv4UsableSize(-1), RangeError);
assertThrows(() => cidrv4UsableSize(33), RangeError);

Parameters

prefixLength: PrefixLengthv4

The CIDR prefix length (0-32)

Return Type

number

The number of assignable addresses

Throws

RangeError

If the prefix length is out of range (not 0-32)

cidrv4UsableSize(cidrOrPrefixLength: Cidrv4 | PrefixLengthv4): number

Returns the number of assignable addresses for either a CIDR block or a prefix length.

Parameters

cidrOrPrefixLength: Cidrv4 | PrefixLengthv4

A Cidrv4 block or a prefix length (0-32)

Return Type

number

The number of assignable addresses