addressVersion(address: string): IpVersion | undefined
Reports which IP version a plain address string is written in.
Returns 4 for dotted decimal, 6 for colon-hexadecimal, and undefined
for anything else — never 0, so the answer cannot be mistaken for a
version number in a numeric context.
The answer describes the string, not the value it would parse to. An
IPv4-mapped IPv6 address such as ::ffff:10.1.2.3 is written as IPv6 and
reports 6, even though parseAddress unwraps it to an IPv4 number.
Version n always means "parseAddressv4 / parseAddressv6 for that
version accepts this string". To get the version of an already parsed
value, use typeof — number is IPv4, bigint is IPv6.
CIDR notation is not an address — use cidrVersion for that.
What counts as valid is exactly what isValidAddressv4 and
isValidAddressv6 accept, which is the grammar each address RFC
publishes and nothing else (see ADR 0003). Surrounding whitespace and
trailing text are not part of either grammar, so addressVersion(" 10.1.2.3")
and addressVersion("1.2.3.4abc") are both undefined.
Both versions and the reject case
Both versions and the reject case
import { assertEquals } from "@std/assert"; import { addressVersion } from "@hertzg/ip/version"; assertEquals(addressVersion("10.1.2.3"), 4); assertEquals(addressVersion("::1"), 6); assertEquals(addressVersion("fe80::1%eth0"), 6); assertEquals(addressVersion("notanip"), undefined); assertEquals(addressVersion("10.0.0.0/8"), undefined);
IPv4-mapped IPv6 is written as IPv6
IPv4-mapped IPv6 is written as IPv6
import { assertEquals } from "@std/assert"; import { addressVersion } from "@hertzg/ip/version"; import { parseAddress } from "@hertzg/ip/address"; assertEquals(addressVersion("::ffff:10.1.2.3"), 6); assertEquals(typeof parseAddress("::ffff:10.1.2.3").address, "number");
IpVersion | undefined
4, 6, or undefined if the string is not a plain IP address