IP version detection for address and CIDR strings.

This module provides addressVersion and cidrVersion, which report whether a string is written as IPv4 or IPv6, or undefined when it is neither. They answer in one call what would otherwise take two version-specific validity checks before picking a parser.

Examples

Dispatching on the IP version

import { assertEquals } from "@std/assert";
import { addressVersion } from "@hertzg/ip/version";
import { parseAddressv4 } from "@hertzg/ip/addressv4";
import { parseAddressv6 } from "@hertzg/ip/addressv6";

const describe = (input: string): string => {
  switch (addressVersion(input)) {
    case 4:
      return `v4:${parseAddressv4(input).address}`;
    case 6:
      return `v6:${parseAddressv6(input).address}`;
    default:
      return "not an address";
  }
};

assertEquals(describe("10.0.0.1"), "v4:167772161");
assertEquals(describe("::1"), "v6:1");
assertEquals(describe("nonsense"), "not an address");

Functions

f
addressVersion(address: string): IpVersion | undefined

Reports which IP version a plain address string is written in.

f
cidrVersion(cidr: string): IpVersion | undefined

Reports which IP version a CIDR notation string is written in.

Type Aliases

T
IpVersion = 4 | 6

An IP version number: 4 for IPv4, 6 for IPv6.