function parseCidrv4
parseCidrv4(cidr: string): ParsedCidrv4

Parses IPv4 CIDR notation, in either dialect and with an optional zone ID, to a ParsedCidrv4.

The notation is address [ "%" zoneId ] "/" prefix (ADR 0003). The address is parsed as parseAddressv4 does, zone included. The prefix is a prefix length when it is decimal digits (no leading zero, no sign, no whitespace, no trailing text; 0 to 32), and a network mask when it contains a ., parsed with the same rules as an address. A mask is stored as given and is not required to be contiguous (ADR 0006): 10.0.0.0/255.0.0.255 parses, and only cidrv4PrefixLength rejects it, because that is the call with no answer. An IPv6 mask on an IPv4 address (10.0.0.0/ffff:ff00::) is rejected.

Examples

Basic CIDR parsing

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

assertEquals(parseCidrv4("192.168.1.0/24"), { address: 3232235776, prefixLength: 24 });

The mask dialect is stored as a mask

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

assertEquals(parseCidrv4("192.168.1.0/255.255.255.0"), { address: 3232235776, mask: 0xFFFFFF00 });
assertEquals(parseCidrv4("10.0.0.0/255.0.0.255"), { address: 167772160, mask: 0xFF0000FF });

A zone ID is carried verbatim

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

assertEquals(parseCidrv4("10.155.101.0%ether1/24"), {
  address: 177956096,
  prefixLength: 24,
  zoneId: "ether1",
});

Error handling

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

assertThrows(() => parseCidrv4("192.168.1.0"), TypeError);
assertThrows(() => parseCidrv4("192.168.1.0/"), TypeError);
assertThrows(() => parseCidrv4("192.168.1.0/33"), RangeError);
assertThrows(() => parseCidrv4("256.0.0.0/24"), RangeError);
assertThrows(() => parseCidrv4("192.168.1.0/024"), TypeError);
assertThrows(() => parseCidrv4("192.168.1.0/ffff:ff00::"), TypeError);
assertThrows(() => parseCidrv4("192.168.1.0/24%ether1"), TypeError);
assertThrows(() => parseCidrv4("2001:db8::/32"), TypeError);

Parameters

cidr: string

The CIDR notation string, e.g. "192.168.1.0/24", "10.0.0.0/255.0.0.0", "10.0.0.1%ether1/32"

Return Type

The address and prefix length or mask as written, and the zone ID if there was one

Throws

TypeError

If the format is invalid: no prefix, a malformed address, prefix length or mask, a mask of the other version, an empty or malformed zone ID

RangeError

If a prefix length is a well-formed number outside 0 to 32, or an octet is greater than 255