// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A 128-bit IPv6 address, stored as sixteen octets in network (big-endian) //! order. //! //! The address is a pure network-layer address: it carries no port, no zone //! identifier and no prefix length. See `Ipv6Network` for CIDR networks, and //! `parseZoned` for text that carries a zone. const std = @import("std"); const json = @import("json.zig"); const Writer = std.Io.Writer; const Ipv4Address = @import("Ipv4Address.zig"); const sockaddr = @import("sockaddr.zig"); const Scope = @import("scope.zig").Scope; const Ipv6Address = @This(); /// Address octets in network byte order: `octets[0]` is the most significant. octets: [16]u8, /// Width of an IPv6 address in bits. pub const bit_count = 128; /// The unspecified address, `::`. pub const unspecified: Ipv6Address = .{ .octets = @splat(0) }; /// The loopback address, `::1`. pub const loopback: Ipv6Address = .{ .octets = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } }; /// Builds an address from its eight 16-bit groups, most significant first. pub fn init(value: [8]u16) Ipv6Address { var octets: [16]u8 = undefined; for (value, 0..) |group, i| { std.mem.writeInt(u16, octets[i * 2 ..][0..2], group, .big); } return .{ .octets = octets }; } /// The eight 16-bit groups of the address, most significant first. pub fn groups(a: Ipv6Address) [8]u16 { var result: [8]u16 = undefined; for (&result, 0..) |*group, i| { group.* = std.mem.readInt(u16, a.octets[i * 2 ..][0..2], .big); } return result; } /// Builds an address from its numeric value, where 1 is `::1`. pub fn fromInt(value: u128) Ipv6Address { var octets: [16]u8 = undefined; std.mem.writeInt(u128, &octets, value, .big); return .{ .octets = octets }; } /// The numeric value of the address, where `::1` is 1. pub fn toInt(a: Ipv6Address) u128 { return std.mem.readInt(u128, &a.octets, .big); } /// The next address, or null at the top of the address space, where there is /// no next one. /// /// An address is a point in a flat 128-bit space and this steps through it; /// whatever network the address happens to belong to has no bearing on which /// address follows it, so `next` will walk straight out of a network without /// noticing. A walk that should stop at a network's edge wants /// `Ipv6Network.addresses` or `Ipv6Network.hosts`, which know where to stop. pub fn next(a: Ipv6Address) ?Ipv6Address { return a.add(1); } /// The previous address, or null at the bottom of the address space. pub fn prev(a: Ipv6Address) ?Ipv6Address { return a.sub(1); } /// The address `delta` further up, or null when that would run off the top of /// the address space. Saturating instead of stopping is `orelse`: /// /// ``` /// const capped = address.add(delta) orelse Ipv6Address.fromInt(std.math.maxInt(u128)); /// ``` pub fn add(a: Ipv6Address, delta: u128) ?Ipv6Address { const sum, const overflow = @addWithOverflow(a.toInt(), delta); return if (overflow == 1) null else .fromInt(sum); } /// The address `delta` further down, or null when that would run off the /// bottom of the address space. pub fn sub(a: Ipv6Address, delta: u128) ?Ipv6Address { const difference, const underflow = @subWithOverflow(a.toInt(), delta); return if (underflow == 1) null else .fromInt(difference); } pub const ParseError = error{ /// A character other than a hexadecimal digit, `:` or `.` was found. InvalidCharacter, /// A group held more than four hexadecimal digits. GroupTooLong, /// A group was empty, as in `1:::2` or a stray leading or trailing `:`. EmptyGroup, /// The text held fewer than eight groups and had no `::` to fill the rest. TooFewGroups, /// The text held more than eight groups. TooManyGroups, /// More than one `::` appeared; the compressed run would be ambiguous. MultipleEllipses, /// A `::` compressed no groups at all, as in `1:2:3:4:5:6:7:8::`. RFC 4291 /// requires `::` to stand for at least one group of zeros. RedundantEllipsis, /// A dotted-quad tail appeared somewhere other than the end of the address. MisplacedIpv4, /// The dotted-quad tail was not a valid IPv4 address. InvalidEmbeddedIpv4, /// The text carried a zone identifier (`%eth0`). Use `parseZoned` to accept /// one. UnexpectedZone, /// A `%` was present but the zone identifier following it was empty. EmptyZone, /// A square bracket appeared on only one end of the address, or text /// followed the closing bracket. Only returned when brackets are allowed; /// otherwise a bracket is just an `InvalidCharacter`. UnmatchedBracket, }; /// Options accepted by `parseWithOptions` and `parseZonedWithOptions`. pub const ParseOptions = struct { /// Accept an address wrapped in the square brackets that a URL authority /// puts around it, as in `[2001:db8::1]` (RFC 3986). The bare form is /// still accepted; a bracket on only one end is `error.UnmatchedBracket`. /// /// Only the address itself is parsed. Text outside the brackets, such as /// the `:443` of `[2001:db8::1]:443`, is rejected rather than read as a /// port, so split the authority before calling. allow_brackets: bool = false, }; /// Parses the text form defined by RFC 4291, including `::` compression and a /// trailing dotted-quad as in `::ffff:192.0.2.1`. /// /// Text carrying a zone identifier is rejected; use `parseZoned` for that. /// Square brackets are rejected too; use `parseWithOptions` to accept them. pub fn parse(text: []const u8) ParseError!Ipv6Address { return parseWithOptions(text, .{}); } /// Like `parse`, but with the relaxations in `options` applied. Use this to /// accept the bracketed form a URL authority uses: /// /// ``` /// const address = try Ipv6Address.parseWithOptions("[2001:db8::1]", .{ .allow_brackets = true }); /// ``` pub fn parseWithOptions(text: []const u8, options: ParseOptions) ParseError!Ipv6Address { // Scanned before the brackets come off so that a zone inside them is still // reported as a zone rather than as stray characters. const scanned = scanText(text); if (scanned.percent) return error.UnexpectedZone; const body = try stripBrackets(text, options); // The scan indexed the text with the brackets still on; removing the // opening one shifts everything down by one. A `::` never includes the // bracket itself, so the shifted position is still inside the body. const ellipsis = if (scanned.ellipsis) |e| e - @intFromBool(body.ptr != text.ptr) else null; return parseUnzoned(body, .{ .percent = false, .ellipsis = ellipsis, .multiple = scanned.multiple }); } /// What one pass over the text found. The three separate searches the parser /// needs are folded into a single scan, because on text this short each /// vectorized `std.mem.find*` call costs more in setup than the search. const Scan = struct { /// Whether a `%` appeared anywhere. percent: bool, /// The position of the first `::`, or null. ellipsis: ?usize, /// Whether another `::` follows the first, which makes the compression /// ambiguous. multiple: bool, }; fn scanText(text: []const u8) Scan { // Three simple early-exit loops rather than one loop doing all three jobs: // the simple loops branch predictably and vectorize, and together they // measure faster than the fused form. var result: Scan = .{ .percent = false, .ellipsis = null, .multiple = false }; for (text) |c| { if (c == '%') { result.percent = true; break; } } if (text.len < 2) return result; var i: usize = 0; while (i < text.len - 1) : (i += 1) { if (text[i] == ':' and text[i + 1] == ':') { result.ellipsis = i; break; } } // The search for a second `::` starts past both colons of the first, so // `:::` reads as a `::` followed by a lone colon rather than as two // overlapping ellipses. if (result.ellipsis) |ellipsis| { var j = ellipsis + 2; while (j + 1 < text.len) : (j += 1) { if (text[j] == ':' and text[j + 1] == ':') { result.multiple = true; break; } } } return result; } /// Removes the square brackets that a URL authority puts around an IPv6 /// address, when `options` allows them. Text with no bracket on either end is /// returned unchanged, so the bare form keeps working. fn stripBrackets(text: []const u8, options: ParseOptions) ParseError![]const u8 { if (!options.allow_brackets or text.len == 0) return text; const open = text[0] == '['; const close = text[text.len - 1] == ']'; if (!open and !close) return text; if (!open or !close) return error.UnmatchedBracket; return text[1 .. text.len - 1]; } /// An address together with the zone identifier that followed it. pub const Zoned = struct { address: Ipv6Address, /// The text after `%`, or null when the text carried no zone. This is a /// slice of the text passed to `parseZoned` and does not outlive it. zone: ?[]const u8, }; /// Parses an address that may carry a zone identifier, as in /// `fe80::1%eth0` (RFC 4007). /// /// The zone is returned verbatim, as a slice of `text`; interpreting it as an /// interface name or index is left to the caller. pub fn parseZoned(text: []const u8) ParseError!Zoned { return parseZonedWithOptions(text, .{}); } /// Like `parseZoned`, but with the relaxations in `options` applied. A zone /// belongs inside the brackets, as in `[fe80::1%eth0]`. /// /// The zone is taken verbatim. RFC 6874 writes the `%` of a zone in a URI as /// the escape `%25`, and undoing that escape is left to whatever unescapes the /// rest of the URI: `[fe80::1%25eth0]` yields the zone `25eth0`, not `eth0`. pub fn parseZonedWithOptions(text: []const u8, options: ParseOptions) ParseError!Zoned { const body = try stripBrackets(text, options); if (indexOfPercent(body)) |index| { const zone = body[index + 1 ..]; if (zone.len == 0) return error.EmptyZone; if (indexOfPercent(zone) != null) return error.InvalidCharacter; return .{ .address = try parseUnzoned(body[0..index], null), .zone = zone }; } return .{ .address = try parseUnzoned(body, null), .zone = null }; } /// The position of the first `%`, or null. A plain loop for the same reason /// as `scanText`. fn indexOfPercent(text: []const u8) ?usize { for (text, 0..) |c, i| if (c == '%') return i; return null; } /// Parses an address with no zone and no brackets. `prescan` carries the scan /// a caller already made, so the text is not walked twice; null means scan /// here. fn parseUnzoned(text: []const u8, prescan: ?Scan) ParseError!Ipv6Address { const scanned = prescan orelse scanText(text); var parsed: [8]u16 = @splat(0); if (scanned.ellipsis) |ellipsis| { const head_text = text[0..ellipsis]; const tail_text = text[ellipsis + 2 ..]; if (scanned.multiple) return error.MultipleEllipses; var head: [8]u16 = undefined; var tail: [8]u16 = undefined; // A dotted-quad tail can only be the last element of the whole // address, so it is never allowed in the part before the `::`. const head_len = try parseGroupList(head_text, &head, false); const tail_len = try parseGroupList(tail_text, &tail, true); const total = head_len + tail_len; if (total > 8) return error.TooManyGroups; if (total == 8) return error.RedundantEllipsis; @memcpy(parsed[0..head_len], head[0..head_len]); @memcpy(parsed[8 - tail_len ..], tail[0..tail_len]); } else { const len = try parseGroupList(text, &parsed, true); if (len < 8) return error.TooFewGroups; } return .init(parsed); } /// Parses a run of colon-separated groups, optionally ending in a dotted-quad. /// Returns the number of 16-bit groups written to `out`. fn parseGroupList(text: []const u8, out: *[8]u16, allow_ipv4: bool) ParseError!usize { if (text.len == 0) return 0; var count: usize = 0; var index: usize = 0; while (true) { // One pass over the group: the value accumulates while the characters // are classified, and a bad character only wins over the checks below // because they are deferred until the whole group has been seen. The // classification is a table lookup with the outcomes OR-ed together, // not a branch per character, because hexadecimal digits are spread // over three ranges and the branches for them predict badly. The // accumulator stops after four digits, by which point the group is too // long anyway, so it cannot overflow. const start = index; var value: u16 = 0; var flags: u8 = 0; while (index < text.len and text[index] != ':') : (index += 1) { const class = group_char_table[text[index]]; flags |= class; if (index - start < 4) value = value << 4 | (class & 0xf); } const part = text[start..index]; if (part.len == 0) return error.EmptyGroup; if (flags & dot_flag != 0) { if (!allow_ipv4 or index != text.len) return error.MisplacedIpv4; if (count + 2 > out.len) return error.TooManyGroups; const embedded = Ipv4Address.parse(part) catch return error.InvalidEmbeddedIpv4; out[count] = std.mem.readInt(u16, embedded.octets[0..2], .big); out[count + 1] = std.mem.readInt(u16, embedded.octets[2..4], .big); count += 2; } else { if (count == out.len) return error.TooManyGroups; if (flags & invalid_flag != 0) return error.InvalidCharacter; if (part.len > 4) return error.GroupTooLong; out[count] = value; count += 1; } if (index == text.len) break; index += 1; } return count; } const dot_flag: u8 = 0x40; const invalid_flag: u8 = 0x80; /// Classifies a character inside a group: hexadecimal digits map to their /// value, `.` to `dot_flag`, and everything else to `invalid_flag`. const group_char_table: [256]u8 = blk: { var table: [256]u8 = @splat(invalid_flag); for ('0'..'9' + 1, 0..) |c, v| table[c] = v; for ('a'..'f' + 1, 10..) |c, v| table[c] = v; for ('A'..'F' + 1, 10..) |c, v| table[c] = v; table['.'] = dot_flag; break :blk table; }; /// Whether `text` is a valid IPv6 address, discarding the reason when it is /// not. Parsed with the default options, so neither a zone identifier nor /// square brackets are accepted. pub fn isValid(text: []const u8) bool { _ = parse(text) catch return false; return true; } /// The longest text an IPv6 address can format to, as in /// `ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255`. pub const max_text_len = "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255".len; /// Writes the canonical text form defined by RFC 5952: lowercase, without /// leading zeros in a group, with the longest run of zero groups replaced by /// `::`, and with a dotted-quad tail for IPv4-mapped addresses. Use the `{f}` /// specifier. /// /// The deprecated IPv4-compatible range `::/96` is written in plain hex /// instead, so that ordinary low-valued addresses such as `::3` do not come /// out as `::0.0.0.3`. pub fn format(a: Ipv6Address, w: *Writer) Writer.Error!void { var buffer: [max_text_len]u8 = undefined; try w.writeAll(a.render(&buffer)); } /// Formats into `buffer`, returning the written slice. The buffer must be at /// least `max_text_len` bytes. pub fn bufPrint(a: Ipv6Address, buffer: []u8) error{NoSpaceLeft}![]u8 { // A buffer meeting the documented minimum fits `render`'s word stores // too, so the text is produced directly in the caller's buffer. if (buffer.len >= max_text_len) return a.render(buffer[0..max_text_len]); var rendered: [max_text_len]u8 = undefined; const text = a.render(&rendered); if (buffer.len < text.len) return error.NoSpaceLeft; @memcpy(buffer[0..text.len], text); return buffer[0..text.len]; } /// Renders the canonical form into `buffer`, returning the written slice. /// This is the one place the text is produced; `format` and `bufPrint` both /// go through it rather than through `Writer.print`, whose per-integer /// formatting costs more than the whole address. fn render(a: Ipv6Address, buffer: *[max_text_len]u8) []u8 { const g = a.groups(); if (g[0] == 0 and g[1] == 0 and g[2] == 0 and g[3] == 0 and g[4] == 0 and g[5] == 0xffff) { buffer[0..7].* = "::ffff:".*; const tail = a.embeddedIpv4().bufPrint(buffer[7..]) catch unreachable; return buffer[0 .. 7 + tail.len]; } // Find the leftmost longest run of zero groups, which RFC 5952 requires be // the one that is compressed. A run of a single zero group is written out. var run_start: usize = 0; var run_len: usize = 0; var i: usize = 0; while (i < g.len) { if (g[i] != 0) { i += 1; continue; } var j = i; while (j < g.len and g[j] == 0) j += 1; if (j - i > run_len) { run_start = i; run_len = j - i; } i = j; } if (run_len < 2) run_len = 0; var len: usize = 0; i = 0; while (i < g.len) { if (run_len != 0 and i == run_start) { buffer[len..][0..2].* = "::".*; len += 2; i += run_len; continue; } if (i != 0 and !(run_len != 0 and i == run_start + run_len)) { buffer[len] = ':'; len += 1; } // The group in lowercase hex without leading zeros. All four digit // characters are built and stored as one word, with the leading zeros // shifted out beforehand; only `width` of the stored bytes are kept, // and the extra bytes fit because the hex form never comes within // four bytes of `max_text_len`. This is branchless where a loop over // the digits would mispredict on the varying group widths; `| 1` makes // a zero group one digit wide without a branch. const digits = "0123456789abcdef"; const chars: [4]u8 = .{ digits[g[i] >> 12], digits[g[i] >> 8 & 0xf], digits[g[i] >> 4 & 0xf], digits[g[i] & 0xf], }; const width = (@as(usize, 16) - @clz(g[i] | 1) + 3) / 4; // The first character sits in the low byte, so the shift drops leading // zeros and the little-endian store puts the rest back in text order. const word = std.mem.readInt(u32, &chars, .little); std.mem.writeInt(u32, buffer[len..][0..4], word >> @intCast(8 * (4 - width)), .little); len += width; i += 1; } return buffer[0..len]; } /// The length of the expanded form: eight groups of four digits and the /// seven colons between them. Unlike `max_text_len` it is also the /// *shortest*, since nothing in the expanded form is ever elided. pub const max_expanded_len = 8 * 5 - 1; /// Writes the address with every group at its full four digits and no `::` /// compression, so `2001:db8::1` comes out as /// `2001:0db8:0000:0000:0000:0000:0000:0001`. /// /// This is not the canonical form and is not what `format` writes — RFC 5952 /// is clear that the compressed form is what an address should be published /// as. It is worth having anyway because it is the only form with a fixed /// width, which is what makes addresses line up in a column, sort lexically /// in the same order they sort numerically, and diff a line at a time when a /// configuration is regenerated. An address written one way in one file and /// the other way in another also compares equal only after both have been /// parsed, so a pipeline that must compare text rather than values wants /// every address put through this first. /// /// For a `{f}` placeholder, reach for it through `std.fmt.alt`: /// /// ``` /// try w.print("{f}", .{std.fmt.alt(address, .writeExpanded)}); /// ``` pub fn writeExpanded(a: Ipv6Address, w: *Writer) Writer.Error!void { var buffer: [max_expanded_len]u8 = undefined; try w.writeAll(a.expanded(&buffer) catch unreachable); } /// The expanded form written into `buffer`, returning the written slice. The /// buffer must be at least `max_expanded_len` bytes. See `writeExpanded` for /// what the form is and when to want it. pub fn expanded(a: Ipv6Address, buffer: []u8) error{NoSpaceLeft}![]u8 { if (buffer.len < max_expanded_len) return error.NoSpaceLeft; const digits = "0123456789abcdef"; var len: usize = 0; for (a.groups(), 0..) |group, i| { if (i != 0) { buffer[len] = ':'; len += 1; } buffer[len] = digits[group >> 12]; buffer[len + 1] = digits[group >> 8 & 0xf]; buffer[len + 2] = digits[group >> 4 & 0xf]; buffer[len + 3] = digits[group & 0xf]; len += 4; } return buffer[0..len]; } /// The length of the nibble form: 32 hexadecimal digits and the 31 dots /// between them. pub const max_nibbles_len = 32 * 2 - 1; /// Writes the address as its 32 nibbles, most significant first, separated by /// dots and in lowercase hexadecimal. /// /// 2001:db8::cb01 -> 2.0.0.1.0.d.b.8.0.0. ... .0.0.c.b.0.1 /// /// This is the reverse-DNS name of RFC 3596 §2.5 with the label order not yet /// undone and the suffix not yet added, which `reverseName` does. It is worth /// having on its own because the nibble form turns up where no lookup does: /// SPF's `%{i}` macro expands an IPv6 client to exactly this, and leaves /// reversing it to a separate transformer. pub fn nibbles(a: Ipv6Address, buffer: []u8) error{NoSpaceLeft}![]u8 { if (buffer.len < max_nibbles_len) return error.NoSpaceLeft; const digits = "0123456789abcdef"; var len: usize = 0; for (a.octets) |octet| { if (len != 0) { buffer[len] = '.'; len += 1; } buffer[len] = digits[octet >> 4]; buffer[len + 1] = '.'; buffer[len + 2] = digits[octet & 0xf]; len += 3; } return buffer[0..len]; } /// The longest a reverse-DNS name can be: every nibble and `ip6.arpa`. Unlike /// IPv4's, it is also the *shortest*, since every IPv6 address writes all 32 /// nibbles. pub const max_reverse_name_len = max_nibbles_len + ip6_arpa.len; const ip6_arpa = ".ip6.arpa"; /// Writes the name this address is looked up under in the reverse DNS: the 32 /// nibbles in reverse order followed by `ip6.arpa`, as RFC 3596 §2.5 defines /// it. /// /// 2001:db8::cb01 -> 1.0.b.c.0.0. ... .0.8.b.d.0.1.0.0.2.ip6.arpa /// /// No zero nibble is ever elided, whatever the text form compresses: the /// name is a delegation path and every level of it has to be there. /// /// An IPv4-mapped address gets an `ip6.arpa` name like any other, which is /// almost certainly not the name that answers — convert with `toIpv4Mapped` /// first and ask the IPv4 address for its own. pub fn reverseName(a: Ipv6Address, buffer: []u8) error{NoSpaceLeft}![]u8 { if (buffer.len < max_reverse_name_len) return error.NoSpaceLeft; const digits = "0123456789abcdef"; var len: usize = 0; var i = a.octets.len; while (i > 0) { i -= 1; if (len != 0) { buffer[len] = '.'; len += 1; } // Within an octet the low nibble is the more specific of the two, so // it leads. buffer[len] = digits[a.octets[i] & 0xf]; buffer[len + 1] = '.'; buffer[len + 2] = digits[a.octets[i] >> 4]; len += 3; } buffer[len..][0..ip6_arpa.len].* = ip6_arpa.*; return buffer[0 .. len + ip6_arpa.len]; } /// Writes the reverse-DNS name to `w`, for a caller that is writing a stream /// rather than filling a buffer: the same name `reverseName` produces, with /// the buffer it needs found on the stack instead of by the caller. pub fn writeReverseName(a: Ipv6Address, w: *Writer) Writer.Error!void { var buffer: [max_reverse_name_len]u8 = undefined; // Every IPv6 name is exactly this long, so the only error the name could // report cannot happen. try w.writeAll(a.reverseName(&buffer) catch unreachable); } pub fn eql(a: Ipv6Address, b: Ipv6Address) bool { return std.mem.eql(u8, &a.octets, &b.octets); } /// Orders two addresses by their numeric value. pub fn order(a: Ipv6Address, b: Ipv6Address) std.math.Order { return std.math.order(a.toInt(), b.toInt()); } /// Converts to the standard library's socket address type. pub fn toStdAddress(a: Ipv6Address, port: u16) std.Io.net.Ip6Address { return .{ .bytes = a.octets, .port = port }; } /// Converts from the standard library's socket address type, dropping the /// port, flow label and interface. pub fn fromStdAddress(a: std.Io.net.Ip6Address) Ipv6Address { return .{ .octets = a.bytes }; } /// What reading an address out of a socket address structure can fail on. pub const SockaddrError = sockaddr.Error; /// The `sockaddr_in6` fields an address and a port do not account for. pub const SockaddrOptions = sockaddr.Options; /// Fills in a `sockaddr_in6` through a pointer to one, returning the number of /// bytes written: the `socklen_t` that goes with the pointer. /// /// The pointer may be to a `sockaddr.in6`, or to a `sockaddr` or a /// `sockaddr.storage` large enough to hold one, and may come from `std.posix`, /// `std.c` or `std.os.linux` alike. The whole structure is written, which /// leaves the flow label and the scope identifier zero; a link-local address /// means nothing without a scope, so write one of those with /// `writeSockaddrWithOptions`. pub fn writeSockaddr(a: Ipv6Address, port: u16, sa: anytype) u32 { return sockaddr.writeIpv6(a, port, .{}, sa); } /// Like `writeSockaddr`, but also setting the two fields an address and a port /// say nothing about: the interface a link-local address is scoped to, and the /// flow label. pub fn writeSockaddrWithOptions(a: Ipv6Address, port: u16, sa: anytype, options: SockaddrOptions) u32 { return sockaddr.writeIpv6(a, port, options, sa); } /// Reads an address out of a `sockaddr_in6`, dropping its port, flow label and /// scope identifier. `sockaddrOptions` returns the last two. /// /// `error.UnexpectedAddressFamily` when the structure's `family` is not /// `AF_INET6`. pub fn fromSockaddr(sa: anytype) SockaddrError!Ipv6Address { return (try sockaddr.readIpv6(sa)).address; } /// The flow label and scope identifier a `sockaddr_in6` carries, which an /// address has nowhere to keep. pub fn sockaddrOptions(sa: anytype) SockaddrError!SockaddrOptions { return sockaddr.readIpv6Options(sa); } /// The IPv4 address held in the low 32 bits, whether or not the address is one /// that gives those bits that meaning. fn embeddedIpv4(a: Ipv6Address) Ipv4Address { return .{ .octets = a.octets[12..16].* }; } /// The embedded IPv4 address of an IPv4-mapped address (`::ffff:a.b.c.d`), or /// null for any other address. pub fn toIpv4Mapped(a: Ipv6Address) ?Ipv4Address { return if (a.isIpv4Mapped()) a.embeddedIpv4() else null; } /// The IPv4 address a 6to4 address is built around (RFC 3056), or null for /// any other address. /// /// A 6to4 prefix is `2002:V4ADDR::/48`, so the address says which IPv4 host /// is tunnelling the traffic. That is the one useful thing to know about a /// 6to4 address, and it is why `isGlobal` cannot really answer for the range: /// whether the address is reachable is a question about the IPv4 address in /// it. pub fn sixtofour(a: Ipv6Address) ?Ipv4Address { if (!a.is6to4()) return null; return .{ .octets = a.octets[2..6].* }; } /// What a Teredo address (RFC 4380 §4) says about the tunnel it names. pub const Teredo = struct { /// The Teredo server, which is in the clear. server: Ipv4Address, /// The client's own IPv4 address as the server saw it, returned in the /// clear. client: Ipv4Address, /// The client's UDP port as the server saw it, returned in the clear. port: u16, /// The flags field, whose top bit says whether the client is behind a /// cone NAT. flags: u16, }; /// What a Teredo address carries, or null for any other address. /// /// Teredo packs a whole tunnel endpoint into an address: the server, the /// client's public address and the client's public port. The client's address /// and port are stored complemented, because a NAT that rewrites addresses /// found in payloads would otherwise rewrite these too and break the tunnel; /// they are returned here in the clear. pub fn teredo(a: Ipv6Address) ?Teredo { if (!a.isTeredo()) return null; const g = a.groups(); return .{ .server = .{ .octets = a.octets[4..8].* }, .client = .fromInt(~std.mem.readInt(u32, a.octets[12..16], .big)), .port = ~g[5], .flags = g[4], }; } pub const TranslatedError = error{ /// A prefix length RFC 6052 §2.2 does not define a layout for. Only 32, /// 40, 48, 56, 64 and 96 are. InvalidPrefixLength, /// Bits 64 to 71 were not zero. §2.2 requires them to be, in every one of /// the six layouts, so an address with them set is not an IPv4-embedded /// address whatever else it looks like. ReservedBitsSet, }; /// The IPv4 address embedded in an IPv4-embedded IPv6 address, for a /// translation prefix of `prefix_len` bits (RFC 6052 §2.2). /// /// The layout is not one field but six, because bits 64 to 71 are reserved /// and the address has to step over them. Only a `/32` and a `/96` keep their /// four octets together; a `/40`, `/48` or `/56` is split either side of the /// reserved byte, and a `/64` sits entirely after it. That is the whole /// reason this takes a prefix length rather than working it out: nothing in /// the address says which of the six layouts was used, so a caller that does /// not know its own translation prefix cannot ask this question at all. /// /// The well-known prefix `64:ff9b::/96` that `isIpv4Translated` names is the /// one case where the prefix is known without being configured. pub fn translatedIpv4(a: Ipv6Address, prefix_len: u8) TranslatedError!Ipv4Address { const indices: [4]usize = switch (prefix_len) { 32 => .{ 4, 5, 6, 7 }, 40 => .{ 5, 6, 7, 9 }, 48 => .{ 6, 7, 9, 10 }, 56 => .{ 7, 9, 10, 11 }, 64 => .{ 9, 10, 11, 12 }, 96 => .{ 12, 13, 14, 15 }, else => return error.InvalidPrefixLength, }; if (a.octets[8] != 0) return error.ReservedBitsSet; var octets: [4]u8 = undefined; for (&octets, indices) |*octet, index| octet.* = a.octets[index]; return .{ .octets = octets }; } /// The solicited-node multicast address this address is listened for on /// (RFC 4291 §2.7.1): `ff02::1:ff00:0/104` with the low 24 bits of the /// address appended. /// /// Neighbour discovery asks "who has this address" here rather than on /// all-nodes multicast, so that a host is only interrupted by a query whose /// last 24 bits match one of its own addresses. A host joins this group for /// every address it holds, and a program speaking NDP has to compute it — it /// is the one derived address in IPv6 that comes up constantly and that /// nothing else in this survey of libraries provides. pub fn solicitedNodeMulticast(a: Ipv6Address) Ipv6Address { var octets: [16]u8 = @splat(0); octets[0] = 0xff; octets[1] = 0x02; octets[11] = 0x01; octets[12] = 0xff; octets[13..16].* = a.octets[13..16].*; return .{ .octets = octets }; } /// The modified EUI-64 interface identifier a 48-bit MAC address becomes /// (RFC 4291 appendix A). /// /// `ff fe` is inserted between the OUI and the rest, and the universal/local /// bit — the second-lowest of the first octet — is inverted. That inversion /// is the part everyone gets wrong: IEEE writes the bit as 0 for a globally /// unique address, IPv6 writes it as 1, and nothing but the flip tells the /// two conventions apart. It is why `02:00:5e:...` and `00:00:5e:...` swap /// places on the way in. pub fn interfaceIdentifier(mac: [6]u8) [8]u8 { return .{ mac[0] ^ 0x02, mac[1], mac[2], 0xff, 0xfe, mac[3], mac[4], mac[5] }; } /// The address `mac` gives itself on the `/64` whose network address is /// `prefix`, by stateless autoconfiguration out of a router advertisement /// (RFC 4862, RFC 4291 appendix A). /// /// Only the high 64 bits of `prefix` are read, since that is all a SLAAC /// prefix ever is; whatever is in its low half is replaced. /// /// Addresses formed this way carry the MAC across every network the host /// joins, which is what RFC 8981's temporary addresses exist to avoid. A host /// that has them will not be using this one for outbound traffic, so finding /// it on the wire says something about the host. pub fn fromMac(prefix: Ipv6Address, mac: [6]u8) Ipv6Address { var octets = prefix.octets; octets[8..16].* = interfaceIdentifier(mac); return .{ .octets = octets }; } /// The MAC address an interface identifier was derived from, or null when the /// identifier does not have the `ff fe` in the middle that says it was. /// /// The marker is two bytes, so an identifier that was never derived from a /// MAC has about a one in 65536 chance of answering anyway. Treat this as /// "the address is shaped like a MAC-derived one" rather than as proof. pub fn macFromInterfaceIdentifier(a: Ipv6Address) ?[6]u8 { if (a.octets[11] != 0xff or a.octets[12] != 0xfe) return null; return .{ a.octets[8] ^ 0x02, a.octets[9], a.octets[10], a.octets[13], a.octets[14], a.octets[15], }; } // Classification. The predicates below follow the IANA IPv6 Special-Purpose // Address Registry. /// `::`, the unspecified address. pub fn isUnspecified(a: Ipv6Address) bool { return a.toInt() == 0; } /// `::1`, the loopback address. pub fn isLoopback(a: Ipv6Address) bool { return a.toInt() == 1; } /// `::ffff:0:0/96`, an IPv4 address mapped into the IPv6 space (RFC 4291). pub fn isIpv4Mapped(a: Ipv6Address) bool { const g = a.groups(); return std.mem.eql(u16, g[0..6], &.{ 0, 0, 0, 0, 0, 0xffff }); } /// `::/96`, the deprecated IPv4-compatible form (RFC 4291). `::` and `::1` /// are excluded. pub fn isIpv4Compatible(a: Ipv6Address) bool { const g = a.groups(); return std.mem.eql(u16, g[0..6], &.{ 0, 0, 0, 0, 0, 0 }) and a.toInt() > 1; } /// `64:ff9b::/96`, the well-known prefix for IPv4/IPv6 translation (RFC 6052). pub fn isIpv4Translated(a: Ipv6Address) bool { const g = a.groups(); return std.mem.eql(u16, g[0..6], &.{ 0x64, 0xff9b, 0, 0, 0, 0 }); } /// `64:ff9b:1::/48`, the local-use prefix for IPv4/IPv6 translation /// (RFC 8215). Where the well-known prefix `isIpv4Translated` names is /// globally reachable, this one is for translation within a single network /// and is not. pub fn isIpv4TranslatedLocal(a: Ipv6Address) bool { const g = a.groups(); return std.mem.eql(u16, g[0..3], &.{ 0x64, 0xff9b, 1 }); } /// `100::/64`, the discard-only prefix (RFC 6666). pub fn isDiscard(a: Ipv6Address) bool { const g = a.groups(); return std.mem.eql(u16, g[0..4], &.{ 0x100, 0, 0, 0 }); } /// `100:0:0:1::/64`, the dummy prefix (RFC 9780 §7.1). It is what a protocol /// addresses a packet to when the packet has to be carried somewhere and then /// consumed rather than delivered: the OAM and BFD packets inside an IP/UDP /// encapsulation are sent to an address out of this block, so that the far /// end of the tunnel takes them off the wire instead of forwarding them on. /// Nothing is ever assigned one, which is what makes it safe to use that way. pub fn isDummy(a: Ipv6Address) bool { const g = a.groups(); return std.mem.eql(u16, g[0..4], &.{ 0x100, 0, 0, 1 }); } /// `2001::/23`, the block IANA assigns from for IETF protocol use /// (RFC 2928). Most of what has been assigned out of it is not globally /// reachable — Teredo and the benchmarking block below among them — but /// several assignments within it are, so this predicate answers "was this /// handed out for a protocol" rather than "is this reachable"; `isGlobal` /// knows which of the two it needs. pub fn isProtocolAssignment(a: Ipv6Address) bool { const g = a.groups(); return g[0] == 0x2001 and g[1] & 0xfe00 == 0; } /// `2001::/32`, Teredo (RFC 4380). pub fn isTeredo(a: Ipv6Address) bool { const g = a.groups(); return g[0] == 0x2001 and g[1] == 0; } /// `2001:2::/48`, reserved for benchmarking (RFC 5180). It is the IPv6 /// counterpart of `Ipv4Address.isBenchmarking`'s `198.18.0.0/15`, and exists /// so that a device being measured can be given addresses that will never /// collide with anything real. pub fn isBenchmarking(a: Ipv6Address) bool { const g = a.groups(); return std.mem.eql(u16, g[0..3], &.{ 0x2001, 2, 0 }); } /// `2001:20::/28`, ORCHIDv2 (RFC 7343). pub fn isOrchid(a: Ipv6Address) bool { const g = a.groups(); return g[0] == 0x2001 and g[1] & 0xfff0 == 0x20; } /// `2001:30::/28`, entity tags for the Drone Remote ID Protocol (RFC 9374). /// Like ORCHIDv2 next door, these are cryptographic identifiers that are /// shaped like addresses rather than addresses that route. pub fn isDrip(a: Ipv6Address) bool { const g = a.groups(); return g[0] == 0x2001 and g[1] & 0xfff0 == 0x30; } /// Reserved for use in documentation: `2001:db8::/32` (RFC 3849) and /// `3fff::/20` (RFC 9637). /// /// The second block was allocated because the first is a single /32, which is /// not enough to write an example of anything with more than one network in /// it without reusing addresses. `3fff::/20` holds 4096 such /32s, so an /// author can give every example in a document a prefix of its own. pub fn isDocumentation(a: Ipv6Address) bool { const g = a.groups(); return (g[0] == 0x2001 and g[1] == 0xdb8) or (g[0] == 0x3fff and g[1] & 0xf000 == 0); } /// `2002::/16`, the deprecated 6to4 prefix (RFC 3056). pub fn is6to4(a: Ipv6Address) bool { return a.groups()[0] == 0x2002; } /// `5f00::/16`, segment identifiers for SRv6 (RFC 9602). A SID names a /// function to perform at a node rather than a destination to deliver to, so /// one appears in a routing header without ever being a packet's final /// destination, and it is not globally reachable. pub fn isSegmentRouting(a: Ipv6Address) bool { return a.groups()[0] == 0x5f00; } /// `fc00::/7`, unique local addresses (RFC 4193). pub fn isUniqueLocal(a: Ipv6Address) bool { return a.octets[0] & 0xfe == 0xfc; } /// `fe80::/10`, link-local unicast (RFC 4291). pub fn isLinkLocal(a: Ipv6Address) bool { return a.octets[0] == 0xfe and a.octets[1] & 0xc0 == 0x80; } /// `fec0::/10`, the deprecated site-local range (RFC 3879). Nothing should /// assign one, and the range left the IANA registry when it was deprecated, /// so `isGlobal` does not consult this predicate. It is here so that a /// program meeting such an address in old configuration can say what it is /// rather than treating it as ordinary global unicast. pub fn isSiteLocal(a: Ipv6Address) bool { return a.octets[0] == 0xfe and a.octets[1] & 0xc0 == 0xc0; } /// `ff00::/8`, multicast (RFC 4291). pub fn isMulticast(a: Ipv6Address) bool { return a.octets[0] == 0xff; } /// `2000::/3`, the range from which global unicast addresses are currently /// allocated. Being in this range does not by itself make an address globally /// reachable; see `isGlobal`. pub fn isGlobalUnicast(a: Ipv6Address) bool { return a.octets[0] & 0xe0 == 0x20; } /// The scope of a multicast address, held in the low nibble of the second /// octet (RFC 4291, RFC 7346). pub const MulticastScope = enum(u4) { reserved = 0x0, interface_local = 0x1, link_local = 0x2, realm_local = 0x3, admin_local = 0x4, site_local = 0x5, organization_local = 0x8, global = 0xe, _, }; /// The scope of a multicast address, or null when the address is not /// multicast. pub fn multicastScope(a: Ipv6Address) ?MulticastScope { if (!a.isMulticast()) return null; return @fromBackingInt(@as(u4, @truncate(a.octets[1]))); } /// The blocks inside `2001::/23` that the registry does mark globally /// reachable. The enclosing entry for the whole /23 is marked not reachable, /// so without this the assignments that genuinely route would be hidden by /// the block they were carved out of. /// /// They are `2001:1::1` (Port Control Protocol anycast, RFC 7723), /// `2001:1::2` (TURN anycast, RFC 8155), `2001:1::3` (DNS-SD service /// registration anycast, RFC 9665), `2001:3::/32` (AMT, RFC 7450), /// `2001:4:112::/48` (AS112-v6, RFC 7535), `2001:20::/28` (ORCHIDv2) and /// `2001:30::/28` (DRIP entity tags). fn isReachableProtocolAssignment(a: Ipv6Address) bool { const g = a.groups(); // The three anycast assignments are consecutive single addresses at the // bottom of `2001:1::/32` rather than blocks. const anycast_base = comptime Ipv6Address.init(.{ 0x2001, 1, 0, 0, 0, 0, 0, 0 }).toInt(); const value = a.toInt(); if (value > anycast_base and value <= anycast_base + 3) return true; if (g[1] == 3) return true; if (g[1] == 4 and g[2] == 0x112) return true; return a.isOrchid() or a.isDrip(); } /// Whether the address is globally reachable, meaning it is not covered by any /// entry of the IANA special-purpose registry that is marked as not globally /// reachable. /// /// Multicast addresses are not globally reachable in this sense unless their /// scope is global; test them with `multicastScope` for finer detail. /// /// Two of the answers are judgment calls rather than readings of the /// registry, and are worth knowing about: /// /// * The deprecated IPv4-compatible range `::/96` left the registry along /// with the mechanism that used it, so nothing says it is unreachable. It /// is treated as unreachable anyway, because nothing routes it. /// * 6to4 (`2002::/16`) is recorded as N/A rather than as true or false, /// since whether a 6to4 address is reachable is really a question about /// the IPv4 address embedded in it. It is treated as reachable here, which /// is what Python's `ipaddress` also does. pub fn isGlobal(a: Ipv6Address) bool { if (a.isMulticast()) return a.multicastScope() == .global; if (a.isProtocolAssignment()) return a.isReachableProtocolAssignment(); return !(a.isUnspecified() or a.isLoopback() or a.isIpv4Mapped() or a.isIpv4Compatible() or a.isIpv4TranslatedLocal() or a.isDiscard() or a.isDummy() or a.isDocumentation() or a.isSegmentRouting() or a.isUniqueLocal() or a.isLinkLocal()); } /// The single category this address falls into, which is the classification /// predicates above run in the one order that gets them all right. See /// `Scope` for what the answer means and when to prefer a predicate. pub fn scope(a: Ipv6Address) Scope { if (a.isUnspecified()) return .unspecified; if (a.isLoopback()) return .loopback; if (a.isLinkLocal()) return .link_local; if (a.isSiteLocal()) return .site_local; if (a.isUniqueLocal()) return .private; if (a.isMulticast()) return .multicast; if (a.isDocumentation()) return .documentation; if (a.isBenchmarking()) return .benchmarking; if (a.isGlobal()) return .global; return .special_purpose; } /// Writes the value as a JSON string. See `json.stringify`. pub fn jsonStringify(value: Ipv6Address, jws: anytype) !void { return json.stringify(value, jws); } /// Reads a JSON string with `parse`. See `json.parse` for what happens to the /// reason when the text is rejected. pub fn jsonParse( allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions, ) !Ipv6Address { _ = options; return json.parse(Ipv6Address, allocator, source); } const testing = std.testing; test parse { try testing.expectEqual(Ipv6Address.init(.{ 0, 0, 0, 0, 0, 0, 0, 1 }), try parse("::1")); try testing.expectEqual(Ipv6Address.unspecified, try parse("::")); try testing.expectEqual( Ipv6Address.init(.{ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 1 }), try parse("2001:db8::1"), ); try testing.expectEqual( Ipv6Address.init(.{ 0x2001, 0xdb8, 0x85a3, 0, 0, 0x8a2e, 0x370, 0x7334 }), try parse("2001:0db8:85a3:0000:0000:8a2e:0370:7334"), ); // Uppercase digits are accepted, though they are never produced. try testing.expectEqual( Ipv6Address.init(.{ 0x2001, 0xDB8, 0, 0, 0, 0, 0, 0xABCD }), try parse("2001:DB8::ABCD"), ); try testing.expectEqual( Ipv6Address.init(.{ 1, 2, 3, 4, 5, 6, 7, 8 }), try parse("1:2:3:4:5:6:7:8"), ); // `::` at either end. try testing.expectEqual(Ipv6Address.init(.{ 1, 0, 0, 0, 0, 0, 0, 0 }), try parse("1::")); try testing.expectEqual(Ipv6Address.init(.{ 0, 0, 0, 0, 0, 0, 0, 1 }), try parse("::1")); try testing.expectEqual( Ipv6Address.init(.{ 1, 2, 3, 4, 5, 6, 7, 0 }), try parse("1:2:3:4:5:6:7::"), ); } test "parse embedded IPv4" { try testing.expectEqual( Ipv6Address.init(.{ 0, 0, 0, 0, 0, 0xffff, 0xc000, 0x201 }), try parse("::ffff:192.0.2.1"), ); try testing.expectEqual( Ipv6Address.init(.{ 0, 0, 0, 0, 0, 0, 0x102, 0x304 }), try parse("::1.2.3.4"), ); try testing.expectEqual( Ipv6Address.init(.{ 0x64, 0xff9b, 0, 0, 0, 0, 0x808, 0x808 }), try parse("64:ff9b::8.8.8.8"), ); try testing.expectEqual( Ipv6Address.init(.{ 0, 0, 0, 0, 0, 0xffff, 0xc000, 0x201 }), try parse("0:0:0:0:0:ffff:192.0.2.1"), ); try testing.expectError(error.MisplacedIpv4, parse("::1.2.3.4:5")); try testing.expectError(error.MisplacedIpv4, parse("1.2.3.4::")); try testing.expectError(error.InvalidEmbeddedIpv4, parse("::ffff:1.2.3")); try testing.expectError(error.InvalidEmbeddedIpv4, parse("::ffff:256.0.0.1")); try testing.expectError(error.InvalidEmbeddedIpv4, parse("::ffff:1.2.3.4.5")); } test "parse rejects malformed text" { try testing.expectError(error.TooFewGroups, parse("")); try testing.expectError(error.TooFewGroups, parse("1:2:3:4:5:6:7")); try testing.expectError(error.TooManyGroups, parse("1:2:3:4:5:6:7:8:9")); try testing.expectError(error.TooManyGroups, parse("1::2:3:4:5:6:7:8:9")); try testing.expectError(error.RedundantEllipsis, parse("1:2:3:4:5:6:7:8::")); try testing.expectError(error.RedundantEllipsis, parse("::1:2:3:4:5:6:7:8")); try testing.expectError(error.MultipleEllipses, parse("1::2::3")); try testing.expectError(error.EmptyGroup, parse(":1:2:3:4:5:6:7")); try testing.expectError(error.EmptyGroup, parse("1:2:3:4:5:6:7:")); try testing.expectError(error.EmptyGroup, parse(":::")); try testing.expectError(error.EmptyGroup, parse(":")); try testing.expectError(error.GroupTooLong, parse("12345::")); try testing.expectError(error.InvalidCharacter, parse("::g")); try testing.expectError(error.InvalidCharacter, parse("::1 ")); try testing.expectError(error.InvalidCharacter, parse("0x1::")); try testing.expectError(error.UnexpectedZone, parse("fe80::1%eth0")); } test parseWithOptions { const brackets: ParseOptions = .{ .allow_brackets = true }; // The bracketed form a URL authority uses, and the bare form alongside it. try testing.expectEqual(loopback, try parseWithOptions("[::1]", brackets)); try testing.expectEqual(loopback, try parseWithOptions("::1", brackets)); try testing.expectEqual( try parse("2001:db8::1"), try parseWithOptions("[2001:db8::1]", brackets), ); try testing.expectEqual( try parse("::ffff:192.0.2.1"), try parseWithOptions("[::ffff:192.0.2.1]", brackets), ); // Brackets stay an error by default, as an ordinary stray character. try testing.expectError(error.InvalidCharacter, parse("[::1]")); try testing.expectError(error.InvalidCharacter, parseWithOptions("[::1]", .{})); // One bracket is never enough, and nothing may follow the closing one. try testing.expectError(error.UnmatchedBracket, parseWithOptions("[::1", brackets)); try testing.expectError(error.UnmatchedBracket, parseWithOptions("::1]", brackets)); try testing.expectError(error.UnmatchedBracket, parseWithOptions("[", brackets)); try testing.expectError(error.UnmatchedBracket, parseWithOptions("]", brackets)); // A port is not an address; the authority has to be split first. try testing.expectError(error.UnmatchedBracket, parseWithOptions("[::1]:443", brackets)); // Only one layer comes off, and the contents still have to parse. try testing.expectError(error.InvalidCharacter, parseWithOptions("[[::1]]", brackets)); try testing.expectError(error.TooFewGroups, parseWithOptions("[]", brackets)); try testing.expectError(error.TooFewGroups, parseWithOptions("[1:2:3]", brackets)); // A zone inside the brackets is still reported as a zone. try testing.expectError(error.UnexpectedZone, parseWithOptions("[fe80::1%eth0]", brackets)); } test parseZonedWithOptions { const brackets: ParseOptions = .{ .allow_brackets = true }; const zoned = try parseZonedWithOptions("[fe80::1%eth0]", brackets); try testing.expectEqual(try parse("fe80::1"), zoned.address); try testing.expectEqualStrings("eth0", zoned.zone.?); const bare = try parseZonedWithOptions("[fe80::1]", brackets); try testing.expectEqual(null, bare.zone); // The RFC 6874 escape is not undone: the zone comes back verbatim. const escaped = try parseZonedWithOptions("[fe80::1%25eth0]", brackets); try testing.expectEqualStrings("25eth0", escaped.zone.?); // The zone belongs inside the brackets. try testing.expectError(error.UnmatchedBracket, parseZonedWithOptions("[fe80::1]%eth0", brackets)); try testing.expectError(error.EmptyZone, parseZonedWithOptions("[fe80::1%]", brackets)); try testing.expectError(error.InvalidCharacter, parseZoned("[fe80::1%eth0]")); } test parseZoned { const zoned = try parseZoned("fe80::1%eth0"); try testing.expectEqual(Ipv6Address.init(.{ 0xfe80, 0, 0, 0, 0, 0, 0, 1 }), zoned.address); try testing.expectEqualStrings("eth0", zoned.zone.?); const numeric = try parseZoned("fe80::1%3"); try testing.expectEqualStrings("3", numeric.zone.?); const bare = try parseZoned("::1"); try testing.expectEqual(Ipv6Address.loopback, bare.address); try testing.expectEqual(null, bare.zone); try testing.expectError(error.EmptyZone, parseZoned("fe80::1%")); try testing.expectError(error.EmptyGroup, parseZoned("fe80:%eth0")); } test jsonStringify { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try std.json.Stringify.value(try Ipv6Address.parse("2001:db8::1"), .{}, &w); // A JSON string holding exactly what `format` would have written. try testing.expectEqualStrings("\"2001:db8::1\"", w.buffered()); } test jsonParse { // The hook is driven directly rather than through `parseFromSlice`, so // that this tests the function it is named after and nothing else; // `root.zig` has the end-to-end one. var scanner = std.json.Scanner.initCompleteInput(testing.allocator, "\"2001:db8::1\""); defer scanner.deinit(); const value = try Ipv6Address.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Ipv6Address.parse("2001:db8::1"))); // As strict inside a JSON document as anywhere else, though the reason is // flattened to `InvalidCharacter` on the way out. var bad = std.json.Scanner.initCompleteInput(testing.allocator, "\"2001:db8:::1\""); defer bad.deinit(); try testing.expectError( error.InvalidCharacter, Ipv6Address.jsonParse(testing.allocator, &bad, .{}), ); // Anything that is not a string is the wrong shape rather than a bad // address. var number = std.json.Scanner.initCompleteInput(testing.allocator, "42"); defer number.deinit(); try testing.expectError( error.UnexpectedToken, Ipv6Address.jsonParse(testing.allocator, &number, .{}), ); } test format { try testing.expectFmt("::", "{f}", .{Ipv6Address.unspecified}); try testing.expectFmt("::1", "{f}", .{Ipv6Address.loopback}); try testing.expectFmt("2001:db8::1", "{f}", .{try parse("2001:0db8:0000:0000:0000:0000:0000:0001")}); try testing.expectFmt("1:2:3:4:5:6:7:8", "{f}", .{try parse("1:2:3:4:5:6:7:8")}); // A single zero group is written out rather than compressed. try testing.expectFmt("1:2:3:4:5:6:0:8", "{f}", .{try parse("1:2:3:4:5:6:0:8")}); // The longest run wins; ties go to the leftmost run. try testing.expectFmt("1:0:0:4::8", "{f}", .{try parse("1:0:0:4:0:0:0:8")}); try testing.expectFmt("1::4:0:0:7:8", "{f}", .{try parse("1:0:0:4:0:0:7:8")}); try testing.expectFmt("fe80::", "{f}", .{try parse("fe80::")}); try testing.expectFmt("::ffff:192.0.2.1", "{f}", .{try parse("::ffff:c000:201")}); // The deprecated IPv4-compatible range stays in hex. try testing.expectFmt("::102:304", "{f}", .{try parse("::1.2.3.4")}); try testing.expectFmt("::3", "{f}", .{try parse("::3")}); try testing.expectFmt("abcd:ef01::", "{f}", .{try parse("ABCD:EF01::")}); } test "round trip through text and integer" { const cases = [_][]const u8{ "::", "::1", "2001:db8::1", "1:2:3:4:5:6:7:8", "fe80::1", "ff02::1", "::ffff:192.0.2.1", "1:0:0:4::8", }; for (cases) |text| { const address = try parse(text); var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings(text, try address.bufPrint(&buffer)); try testing.expectEqual(address, Ipv6Address.fromInt(address.toInt())); try testing.expectEqual(address, Ipv6Address.init(address.groups())); } try testing.expectEqual(@as(u128, 1), Ipv6Address.loopback.toInt()); } test "classification" { try testing.expect(Ipv6Address.loopback.isLoopback()); try testing.expect(Ipv6Address.unspecified.isUnspecified()); try testing.expect((try parse("fe80::1")).isLinkLocal()); try testing.expect((try parse("febf::1")).isLinkLocal()); try testing.expect(!(try parse("fec0::1")).isLinkLocal()); try testing.expect((try parse("fc00::1")).isUniqueLocal()); try testing.expect((try parse("fd12:3456::1")).isUniqueLocal()); try testing.expect(!(try parse("fe00::1")).isUniqueLocal()); try testing.expect((try parse("ff02::1")).isMulticast()); try testing.expect((try parse("2001:db8::1")).isDocumentation()); try testing.expect((try parse("2002::1")).is6to4()); try testing.expect((try parse("2001::1")).isTeredo()); try testing.expect((try parse("2001:20::1")).isOrchid()); try testing.expect((try parse("100::1")).isDiscard()); try testing.expect((try parse("64:ff9b::1.2.3.4")).isIpv4Translated()); try testing.expect((try parse("::ffff:1.2.3.4")).isIpv4Mapped()); try testing.expect((try parse("::1.2.3.4")).isIpv4Compatible()); try testing.expect(!Ipv6Address.loopback.isIpv4Compatible()); try testing.expect((try parse("2606:4700::1")).isGlobalUnicast()); try testing.expectEqual(.link_local, (try parse("ff02::1")).multicastScope().?); try testing.expectEqual(.global, (try parse("ff0e::1")).multicastScope().?); try testing.expectEqual(.interface_local, (try parse("ff01::1")).multicastScope().?); try testing.expectEqual(null, (try parse("2001:db8::1")).multicastScope()); try testing.expect((try parse("2606:4700::1")).isGlobal()); try testing.expect((try parse("ff0e::1")).isGlobal()); try testing.expect(!(try parse("ff02::1")).isGlobal()); try testing.expect(!(try parse("2001:db8::1")).isGlobal()); try testing.expect(!(try parse("fd00::1")).isGlobal()); try testing.expect(!Ipv6Address.loopback.isGlobal()); } test toIpv4Mapped { try testing.expectEqual(Ipv4Address.init(1, 2, 3, 4), (try parse("::ffff:1.2.3.4")).toIpv4Mapped().?); try testing.expectEqual(null, (try parse("2001:db8::1")).toIpv4Mapped()); try testing.expectEqual(null, (try parse("::1.2.3.4")).toIpv4Mapped()); } test "ordering" { try testing.expectEqual(.lt, Ipv6Address.unspecified.order(.loopback)); try testing.expectEqual(.eq, Ipv6Address.loopback.order(.loopback)); try testing.expectEqual(.gt, (try parse("2001:db8::2")).order(try parse("2001:db8::1"))); try testing.expect(Ipv6Address.loopback.eql(.init(.{ 0, 0, 0, 0, 0, 0, 0, 1 }))); } test "the nibble form" { var buffer: [max_nibbles_len]u8 = undefined; try testing.expectEqualStrings( "4.3.2.1.0.0.0.0.0.0.0.1.0.0.0.2.0.0.0.3.0.0.0.4.0.5.6.7.8.9.a.b", try (try parse("4321:0:1:2:3:4:567:89ab")).nibbles(&buffer), ); // Every nibble is written, whatever the text form compresses away. try testing.expectEqualStrings( "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1", try loopback.nibbles(&buffer), ); try testing.expectEqual(max_nibbles_len, (try loopback.nibbles(&buffer)).len); var small: [max_nibbles_len - 1]u8 = undefined; try testing.expectError(error.NoSpaceLeft, loopback.nibbles(&small)); } test "reverse-DNS names" { var buffer: [max_reverse_name_len]u8 = undefined; // RFC 3596 §2.5's own example, in the lowercase this library writes. try testing.expectEqualStrings( "b.a.9.8.7.6.5.0.4.0.0.0.3.0.0.0.2.0.0.0.1.0.0.0.0.0.0.0.1.2.3.4.ip6.arpa", try (try parse("4321:0:1:2:3:4:567:89ab")).reverseName(&buffer), ); try testing.expectEqualStrings( "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa", try loopback.reverseName(&buffer), ); // Every address writes all 32 nibbles, so the longest name is also the // shortest and `max_reverse_name_len` is exact rather than an upper // bound. try testing.expectEqual( max_reverse_name_len, (try unspecified.reverseName(&buffer)).len, ); // The reverse name is the nibble form read backwards, which is the one // property worth checking rather than transcribing. var nibble_buffer: [max_nibbles_len]u8 = undefined; const address = try parse("2001:db8::cb01"); const forward = try address.nibbles(&nibble_buffer); const reverse = try address.reverseName(&buffer); var i: usize = 0; while (i < max_nibbles_len) : (i += 2) { try testing.expectEqual(forward[i], reverse[max_nibbles_len - 1 - i]); } try testing.expect(std.mem.endsWith(u8, reverse, ".ip6.arpa")); var small: [max_reverse_name_len - 1]u8 = undefined; try testing.expectError(error.NoSpaceLeft, loopback.reverseName(&small)); } test "reverse-DNS names written to a writer" { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try loopback.writeReverseName(&w); try testing.expectEqualStrings( "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa", w.buffered(), ); // The writer form and the buffer form produce the same name, which is // the whole of what it promises. var name: [max_reverse_name_len]u8 = undefined; const address = try parse("2001:db8::cb01"); w = .fixed(&buffer); try address.writeReverseName(&w); try testing.expectEqualStrings(try address.reverseName(&name), w.buffered()); // A writer with no room left reports it rather than truncating. var full: [max_reverse_name_len - 1]u8 = undefined; var short: Writer = .fixed(&full); try testing.expectError(error.WriteFailed, address.writeReverseName(&short)); } test init { const address: Ipv6Address = .init(.{ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 1 }); try testing.expect(address.eql(try .parse("2001:db8::1"))); try testing.expectEqual(@as(u8, 0x20), address.octets[0]); } test groups { const address = try parse("2001:db8::1"); try testing.expectEqualSlices( u16, &.{ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 1 }, &address.groups(), ); } test fromInt { try testing.expect(Ipv6Address.fromInt(1).eql(.loopback)); try testing.expect(Ipv6Address.fromInt(0).eql(.unspecified)); } test toInt { try testing.expectEqual(@as(u128, 1), Ipv6Address.loopback.toInt()); // The numeric value orders addresses the way the text form reads. try testing.expect((try parse("2001:db8::1")).toInt() < (try parse("2001:db8::2")).toInt()); } test isValid { try testing.expect(isValid("2001:db8::1")); try testing.expect(isValid("::")); try testing.expect(!isValid("2001:db8:::1")); // The default options accept neither brackets nor a zone. try testing.expect(!isValid("[2001:db8::1]")); try testing.expect(!isValid("fe80::1%eth0")); } test bufPrint { var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings("2001:db8::1", try (try parse("2001:db8::1")).bufPrint(&buffer)); // Too small a buffer is the only way it fails. var small: [4]u8 = undefined; try testing.expectError(error.NoSpaceLeft, (try parse("2001:db8::1")).bufPrint(&small)); } test expanded { var buffer: [Ipv6Address.max_expanded_len]u8 = undefined; try testing.expectEqualStrings( "2001:0db8:0000:0000:0000:0000:0000:0001", try (try parse("2001:db8::1")).expanded(&buffer), ); // Every address is the same width, `::` included. try testing.expectEqualStrings( "0000:0000:0000:0000:0000:0000:0000:0000", try Ipv6Address.unspecified.expanded(&buffer), ); // An IPv4-mapped address expands to hex rather than to the dotted-quad // tail the canonical form uses, since the point of the form is that every // address is written the same way. try testing.expectEqualStrings( "0000:0000:0000:0000:0000:ffff:c000:0201", try (try parse("::ffff:192.0.2.1")).expanded(&buffer), ); var small: [Ipv6Address.max_expanded_len - 1]u8 = undefined; try testing.expectError(error.NoSpaceLeft, Ipv6Address.loopback.expanded(&small)); } test writeExpanded { var buffer: [64]u8 = undefined; var w: Writer = .fixed(&buffer); try (try parse("fe80::1")).writeExpanded(&w); try testing.expectEqualStrings("fe80:0000:0000:0000:0000:0000:0000:0001", w.buffered()); // Through `std.fmt.alt`, which is how it reaches a `{f}` placeholder. var printed: [64]u8 = undefined; var p: Writer = .fixed(&printed); try p.print("{f}", .{std.fmt.alt(try parse("fe80::1"), .writeExpanded)}); try testing.expectEqualStrings("fe80:0000:0000:0000:0000:0000:0000:0001", p.buffered()); } test nibbles { var buffer: [max_nibbles_len]u8 = undefined; // Every nibble, most significant first, with nothing elided and no suffix. try testing.expectEqualStrings( "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1", try Ipv6Address.loopback.nibbles(&buffer), ); } test reverseName { var buffer: [max_reverse_name_len]u8 = undefined; try testing.expectEqualStrings( "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa", try Ipv6Address.loopback.reverseName(&buffer), ); } test writeReverseName { var buffer: [max_reverse_name_len]u8 = undefined; var w: Writer = .fixed(&buffer); try Ipv6Address.loopback.writeReverseName(&w); try testing.expect(std.mem.endsWith(u8, w.buffered(), ".ip6.arpa")); try testing.expectEqual(max_reverse_name_len, w.buffered().len); } test next { try testing.expect((try parse("2001:db8::1")).next().?.eql(try .parse("2001:db8::2"))); // Across a group boundary, and out of the network, without noticing // either: the space is flat. try testing.expect((try parse("2001:db8::ffff")).next().?.eql(try .parse("2001:db8::1:0"))); try testing.expectEqual(null, Ipv6Address.fromInt(std.math.maxInt(u128)).next()); } test prev { try testing.expect((try parse("2001:db8::1:0")).prev().?.eql(try .parse("2001:db8::ffff"))); try testing.expectEqual(null, Ipv6Address.unspecified.prev()); } test add { try testing.expect((try parse("2001:db8::")).add(0xffff).?.eql(try .parse("2001:db8::ffff"))); // Null rather than wrapping round to the bottom of the space. try testing.expectEqual(null, Ipv6Address.fromInt(std.math.maxInt(u128)).add(1)); } test sub { try testing.expect((try parse("2001:db8::ffff")).sub(0xffff).?.eql(try .parse("2001:db8::"))); try testing.expectEqual(null, Ipv6Address.unspecified.sub(1)); } test eql { try testing.expect((try parse("2001:db8::1")).eql(try .parse("2001:0db8:0000::0001"))); try testing.expect(!(try parse("2001:db8::1")).eql(try .parse("2001:db8::2"))); } test order { try testing.expectEqual(.lt, (try parse("::1")).order(try .parse("::2"))); try testing.expectEqual(.eq, (try parse("::1")).order(try .parse("::1"))); try testing.expectEqual(.gt, (try parse("2001:db8::")).order(try .parse("::ffff:ffff"))); } test toStdAddress { const socket = (try parse("2001:db8::1")).toStdAddress(443); try testing.expectEqual(@as(u16, 443), socket.port); try testing.expect(fromStdAddress(socket).eql(try .parse("2001:db8::1"))); } test fromStdAddress { const address = fromStdAddress((try parse("2001:db8::1")).toStdAddress(443)); try testing.expect(address.eql(try .parse("2001:db8::1"))); } test writeSockaddr { var sa: std.posix.sockaddr.in6 = undefined; const len = (try parse("2001:db8::1")).writeSockaddr(443, &sa); try testing.expectEqual(@as(u32, @sizeOf(std.posix.sockaddr.in6)), len); try testing.expect((try fromSockaddr(&sa)).eql(try .parse("2001:db8::1"))); // The flow label and the scope are left at zero. try testing.expectEqual(SockaddrOptions{}, try sockaddrOptions(&sa)); } test writeSockaddrWithOptions { var sa: std.posix.sockaddr.in6 = undefined; // `fe80::1` means nothing without the interface it is scoped to, which is // what the options carry. _ = (try parse("fe80::1")).writeSockaddrWithOptions(22, &sa, .{ .scope_id = 2 }); try testing.expectEqual(@as(u32, 2), sa.scope_id); try testing.expect((try fromSockaddr(&sa)).eql(try .parse("fe80::1"))); } test fromSockaddr { var sa: std.posix.sockaddr.in6 = undefined; _ = Ipv6Address.loopback.writeSockaddr(0, &sa); try testing.expect((try fromSockaddr(&sa)).eql(.loopback)); // A structure of any other family is reported rather than misread. sa.family = std.posix.AF.INET; try testing.expectError(error.UnexpectedAddressFamily, fromSockaddr(&sa)); } test sockaddrOptions { var sa: std.posix.sockaddr.in6 = undefined; _ = (try parse("fe80::1")).writeSockaddrWithOptions(22, &sa, .{ .scope_id = 3, .flowinfo = 7 }); try testing.expectEqual( SockaddrOptions{ .scope_id = 3, .flowinfo = 7 }, try sockaddrOptions(&sa), ); } test sixtofour { // `2002:V4ADDR::/48`, so the two groups after the prefix are the address. try testing.expect((try parse("2002:c000:204::1")).sixtofour().? .eql(try .parse("192.0.2.4"))); try testing.expectEqual(null, (try parse("2001:db8::1")).sixtofour()); } test teredo { // The example everyone cites: a client behind a cone NAT. const t = (try parse("2001:0:4136:e378:8000:63bf:3fff:fdd2")).teredo().?; try testing.expect(t.server.eql(try .parse("65.54.227.120"))); // Client address and port come out of the address complemented, and are // handed back in the clear. try testing.expect(t.client.eql(try .parse("192.0.2.45"))); try testing.expectEqual(@as(u16, 40000), t.port); try testing.expectEqual(@as(u16, 0x8000), t.flags); try testing.expectEqual(null, (try parse("2001:db8::1")).teredo()); } test translatedIpv4 { // The six layouts, checked against the worked table in RFC 6052 §2.4. // Every one of them holds 192.0.2.33; what differs is where. const expected = try Ipv4Address.parse("192.0.2.33"); const cases = [_]struct { prefix_len: u8, text: []const u8 }{ .{ .prefix_len = 32, .text = "2001:db8:c000:221::" }, .{ .prefix_len = 40, .text = "2001:db8:1c0:2:21::" }, .{ .prefix_len = 48, .text = "2001:db8:122:c000:2:2100::" }, .{ .prefix_len = 56, .text = "2001:db8:122:3c0:0:221::" }, .{ .prefix_len = 64, .text = "2001:db8:122:344:c0:2:2100::" }, .{ .prefix_len = 96, .text = "2001:db8:122:344::192.0.2.33" }, }; for (cases) |case| { const embedded = try (try parse(case.text)).translatedIpv4(case.prefix_len); try testing.expect(embedded.eql(expected)); } // The well-known prefix is a `/96`, which is the one case where the // length is known without being configured. try testing.expect((try (try parse("64:ff9b::192.0.2.1")).translatedIpv4(96)) .eql(try .parse("192.0.2.1"))); // Nothing in the address says which layout was used, so a length that has // no layout is an error rather than a guess. try testing.expectError( error.InvalidPrefixLength, (try parse("2001:db8::")).translatedIpv4(60), ); // Bits 64 to 71 must be zero in all six. try testing.expectError( error.ReservedBitsSet, (try parse("2001:db8:c000:221:ff00::")).translatedIpv4(32), ); } test solicitedNodeMulticast { // RFC 4291 §2.7.1's own example: the low 24 bits, and nothing else, // decide the group. try testing.expect((try parse("4037::01:800:200e:8c6c")).solicitedNodeMulticast() .eql(try .parse("ff02::1:ff0e:8c6c"))); // Which is the point of it: two addresses sharing their last 24 bits // share a group, however unlike each other they otherwise are. try testing.expect((try parse("fe80::200e:8c6c")).solicitedNodeMulticast() .eql((try parse("4037::01:800:200e:8c6c")).solicitedNodeMulticast())); try testing.expect((try parse("2001:db8::1")).solicitedNodeMulticast().isMulticast()); } test interfaceIdentifier { // RFC 4291 appendix A's example. Note the first octet: 34 goes in and 36 // comes out, because the universal/local bit is inverted. try testing.expectEqual( [_]u8{ 0x36, 0x56, 0x78, 0xff, 0xfe, 0x9a, 0xbc, 0xde }, Ipv6Address.interfaceIdentifier(.{ 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde }), ); // A globally unique MAC has that bit clear, so the identifier has it set. try testing.expectEqual( [_]u8{ 0x02, 0x1b, 0x63, 0xff, 0xfe, 0x84, 0x45, 0xe6 }, Ipv6Address.interfaceIdentifier(.{ 0x00, 0x1b, 0x63, 0x84, 0x45, 0xe6 }), ); } test fromMac { const address = Ipv6Address.fromMac( try .parse("2001:db8:1:2::"), .{ 0x00, 0x1b, 0x63, 0x84, 0x45, 0xe6 }, ); try testing.expect(address.eql(try .parse("2001:db8:1:2:21b:63ff:fe84:45e6"))); // Only the high half of the prefix is read; whatever is in its low half // is replaced. try testing.expect(Ipv6Address.fromMac( try .parse("2001:db8:1:2:dead:beef:dead:beef"), .{ 0x00, 0x1b, 0x63, 0x84, 0x45, 0xe6 }, ).eql(address)); } test macFromInterfaceIdentifier { try testing.expectEqual( [_]u8{ 0x00, 0x1b, 0x63, 0x84, 0x45, 0xe6 }, (try parse("2001:db8:1:2:21b:63ff:fe84:45e6")).macFromInterfaceIdentifier(), ); // Null without the `ff fe` marker in the middle, which is all there is to // go on. try testing.expectEqual(null, (try parse("2001:db8::1")).macFromInterfaceIdentifier()); // And it undoes `fromMac` exactly. const mac: [6]u8 = .{ 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde }; try testing.expectEqual( mac, Ipv6Address.fromMac(try .parse("fe80::"), mac).macFromInterfaceIdentifier(), ); } test scope { try testing.expectEqual(.global, (try parse("2606:4700:4700::1111")).scope()); try testing.expectEqual(.private, (try parse("fd00::1")).scope()); try testing.expectEqual(.link_local, (try parse("fe80::1")).scope()); try testing.expectEqual(.multicast, (try parse("ff02::1")).scope()); // Both documentation blocks. try testing.expectEqual(.documentation, (try parse("2001:db8::1")).scope()); try testing.expectEqual(.documentation, (try parse("3fff::1")).scope()); try testing.expectEqual(.benchmarking, (try parse("2001:2::1")).scope()); // Deprecated site-local space is reported as what it is, which is the one // place `scope` and `isGlobal` deliberately disagree. try testing.expectEqual(.site_local, (try parse("fec0::1")).scope()); try testing.expect((try parse("fec0::1")).isGlobal()); // Teredo and the rest of the unreachable registry entries have no // category of their own. try testing.expectEqual(.special_purpose, (try parse("2001:0:1::1")).scope()); try testing.expectEqual(.special_purpose, (try parse("::ffff:192.0.2.1")).scope()); } test isUnspecified { try testing.expect(Ipv6Address.unspecified.isUnspecified()); try testing.expect(!Ipv6Address.loopback.isUnspecified()); } test isLoopback { // Exactly `::1`, where IPv4 has a whole /8. try testing.expect(Ipv6Address.loopback.isLoopback()); try testing.expect(!(try parse("::2")).isLoopback()); } test isIpv4Mapped { try testing.expect((try parse("::ffff:192.0.2.1")).isIpv4Mapped()); try testing.expect(!(try parse("::192.0.2.1")).isIpv4Mapped()); } test isIpv4Compatible { try testing.expect((try parse("::192.0.2.1")).isIpv4Compatible()); // `::` and `::1` are excluded: they are addresses in their own right. try testing.expect(!Ipv6Address.loopback.isIpv4Compatible()); try testing.expect(!Ipv6Address.unspecified.isIpv4Compatible()); } test isIpv4Translated { try testing.expect((try parse("64:ff9b::192.0.2.1")).isIpv4Translated()); try testing.expect(!(try parse("2001:db8::1")).isIpv4Translated()); // The local-use prefix is a different block, one group along. try testing.expect(!(try parse("64:ff9b:1::192.0.2.1")).isIpv4Translated()); } test isIpv4TranslatedLocal { try testing.expect((try parse("64:ff9b:1::192.0.2.1")).isIpv4TranslatedLocal()); try testing.expect(!(try parse("64:ff9b::192.0.2.1")).isIpv4TranslatedLocal()); // The well-known prefix routes; this one does not. try testing.expect((try parse("64:ff9b::192.0.2.1")).isGlobal()); try testing.expect(!(try parse("64:ff9b:1::192.0.2.1")).isGlobal()); } test isDiscard { try testing.expect((try parse("100::1")).isDiscard()); try testing.expect(!(try parse("101::1")).isDiscard()); // The dummy prefix is the next /64 along and is not the discard one. try testing.expect(!(try parse("100:0:0:1::1")).isDiscard()); } test isDummy { try testing.expect((try parse("100:0:0:1::1")).isDummy()); try testing.expect(!(try parse("100::1")).isDummy()); } test isProtocolAssignment { try testing.expect((try parse("2001:0:1::1")).isProtocolAssignment()); try testing.expect((try parse("2001:20::1")).isProtocolAssignment()); // `2001:db8::/32` sits above the /23, which is why documentation // addresses are not protocol assignments. try testing.expect(!(try parse("2001:db8::1")).isProtocolAssignment()); try testing.expect(!(try parse("2001:200::1")).isProtocolAssignment()); } test isTeredo { try testing.expect((try parse("2001:0:1::1")).isTeredo()); try testing.expect(!(try parse("2001:db8::1")).isTeredo()); } test isBenchmarking { try testing.expect((try parse("2001:2::1")).isBenchmarking()); try testing.expect(!(try parse("2001:3::1")).isBenchmarking()); // `2001:2:1::1` is outside the /48, close as it looks. try testing.expect(!(try parse("2001:2:1::1")).isBenchmarking()); } test isOrchid { try testing.expect((try parse("2001:20::1")).isOrchid()); try testing.expect(!(try parse("2001:30::1")).isOrchid()); } test isDrip { try testing.expect((try parse("2001:30::1")).isDrip()); try testing.expect(!(try parse("2001:20::1")).isDrip()); } test isDocumentation { try testing.expect((try parse("2001:db8::1")).isDocumentation()); try testing.expect(!(try parse("2001:db9::1")).isDocumentation()); // The second block, RFC 9637's. It is a /20, so it runs to // `3fff:0fff:...` and no further: `3fff:1000::` is outside it, however // much it looks like the same prefix. try testing.expect((try parse("3fff::1")).isDocumentation()); try testing.expect((try parse("3fff:fff:ffff:ffff:ffff:ffff:ffff:ffff")).isDocumentation()); try testing.expect(!(try parse("3fff:1000::1")).isDocumentation()); } test is6to4 { try testing.expect((try parse("2002:c000:201::1")).is6to4()); try testing.expect(!(try parse("2003::1")).is6to4()); } test isSegmentRouting { try testing.expect((try parse("5f00::1")).isSegmentRouting()); try testing.expect(!(try parse("5f01::1")).isSegmentRouting()); // A SID is not somewhere a packet can be sent from outside the domain. try testing.expect(!(try parse("5f00::1")).isGlobal()); } test isUniqueLocal { // `fc00::/7`, which is both `fc00::/8` and the `fd00::/8` in common use. try testing.expect((try parse("fd00::1")).isUniqueLocal()); try testing.expect((try parse("fc00::1")).isUniqueLocal()); try testing.expect(!(try parse("fe00::1")).isUniqueLocal()); } test isLinkLocal { try testing.expect((try parse("fe80::1")).isLinkLocal()); try testing.expect(!(try parse("fec0::1")).isLinkLocal()); } test isSiteLocal { try testing.expect((try parse("fec0::1")).isSiteLocal()); try testing.expect((try parse("feff::1")).isSiteLocal()); try testing.expect(!(try parse("fe80::1")).isSiteLocal()); // Deprecated, and out of the registry, so `isGlobal` says nothing about // it either way. try testing.expect((try parse("fec0::1")).isGlobal()); } test isMulticast { try testing.expect((try parse("ff02::1")).isMulticast()); try testing.expect(!(try parse("fe80::1")).isMulticast()); } test isGlobalUnicast { // The range addresses are currently allocated from, which is not the same // question as whether one is reachable. try testing.expect((try parse("2001:db8::1")).isGlobalUnicast()); try testing.expect(!(try parse("fd00::1")).isGlobalUnicast()); try testing.expect(!(try parse("2001:db8::1")).isGlobal()); } test multicastScope { try testing.expectEqual(.link_local, (try parse("ff02::1")).multicastScope()); try testing.expectEqual(.global, (try parse("ff0e::1")).multicastScope()); // Null rather than a scope for anything that is not multicast. try testing.expectEqual(null, (try parse("2001:db8::1")).multicastScope()); } test isGlobal { try testing.expect((try parse("2606:4700:4700::1111")).isGlobal()); try testing.expect(!(try parse("fd00::1")).isGlobal()); try testing.expect(!Ipv6Address.loopback.isGlobal()); // Multicast is global only where its scope says so. try testing.expect((try parse("ff0e::1")).isGlobal()); try testing.expect(!(try parse("ff02::1")).isGlobal()); // Both documentation blocks, and the benchmarking one. try testing.expect(!(try parse("2001:db8::1")).isGlobal()); try testing.expect(!(try parse("3fff::1")).isGlobal()); try testing.expect(!(try parse("2001:2::1")).isGlobal()); // Most of `2001::/23` is unreachable, but not the assignments carved out // of it that route. try testing.expect(!(try parse("2001:0:1::1")).isGlobal()); try testing.expect((try parse("2001:20::1")).isGlobal()); try testing.expect((try parse("2001:1::1")).isGlobal()); } test scanText { // One pass answers all three questions the parser has about the text. try testing.expectEqual( Scan{ .percent = false, .ellipsis = null, .multiple = false }, scanText("1:2:3:4:5:6:7:8"), ); try testing.expectEqual( Scan{ .percent = false, .ellipsis = 4, .multiple = false }, scanText("2001::1"), ); try testing.expectEqual( Scan{ .percent = false, .ellipsis = 1, .multiple = true }, scanText("1::2::3"), ); try testing.expectEqual( Scan{ .percent = true, .ellipsis = 4, .multiple = false }, scanText("fe80::1%eth0"), ); // The second search starts past both colons of the first, so `:::` is a // `::` followed by a lone colon rather than two overlapping ellipses. try testing.expectEqual( Scan{ .percent = false, .ellipsis = 1, .multiple = false }, scanText("1:::2"), ); } test stripBrackets { // Brackets come off only when the options allow them, and the bare form is // returned unchanged either way. try testing.expectEqualStrings("::1", try stripBrackets("[::1]", .{ .allow_brackets = true })); try testing.expectEqualStrings("::1", try stripBrackets("::1", .{ .allow_brackets = true })); try testing.expectEqualStrings("[::1]", try stripBrackets("[::1]", .{})); // A bracket on one end only is a mistake rather than a bare address. try testing.expectError(error.UnmatchedBracket, stripBrackets("[::1", .{ .allow_brackets = true })); try testing.expectError(error.UnmatchedBracket, stripBrackets("::1]", .{ .allow_brackets = true })); } test indexOfPercent { try testing.expectEqual(@as(?usize, 7), indexOfPercent("fe80::1%eth0")); try testing.expectEqual(@as(?usize, null), indexOfPercent("fe80::1")); } test parseUnzoned { // The parser proper, with neither brackets nor a zone left to deal with. try testing.expect((try parseUnzoned("2001:db8::1", null)).eql(try parse("2001:db8::1"))); try testing.expect((try parseUnzoned("::ffff:192.0.2.1", null)).eql(try parse("::ffff:192.0.2.1"))); try testing.expectError(error.MultipleEllipses, parseUnzoned("1::2::3", null)); // A caller that has already scanned the text hands the scan over rather // than have it walked twice. const text = "2001:db8::1"; try testing.expect((try parseUnzoned(text, scanText(text))).eql(try parse(text))); } test parseGroupList { var out: [8]u16 = undefined; try testing.expectEqual(@as(usize, 3), try parseGroupList("2001:db8:1", &out, false)); try testing.expectEqualSlices(u16, &.{ 0x2001, 0xdb8, 1 }, out[0..3]); // A dotted-quad tail counts as the two groups it stands for, and is only // read where one is allowed. try testing.expectEqual(@as(usize, 2), try parseGroupList("192.0.2.1", &out, true)); try testing.expectEqualSlices(u16, &.{ 0xc000, 0x0201 }, out[0..2]); // Empty text is no groups at all, which is what either side of a leading // or trailing `::` gives. try testing.expectEqual(@as(usize, 0), try parseGroupList("", &out, false)); } test render { var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings("2001:db8::1", (try parse("2001:db8::1")).render(&buffer)); // The leftmost longest run of zero groups is the one compressed, and a run // of a single group is written out (RFC 5952). try testing.expectEqualStrings("1:0:2::3", (try parse("1:0:2:0:0:0:0:3")).render(&buffer)); try testing.expectEqualStrings("::", Ipv6Address.unspecified.render(&buffer)); // An IPv4-mapped address gets the dotted-quad tail. try testing.expectEqualStrings("::ffff:192.0.2.1", (try parse("::ffff:192.0.2.1")).render(&buffer)); } test isReachableProtocolAssignment { // The anycast addresses are three, and `2001:1::4` is not one of them. try testing.expect((try parse("2001:1::1")).isReachableProtocolAssignment()); try testing.expect((try parse("2001:1::3")).isReachableProtocolAssignment()); try testing.expect(!(try parse("2001:1::4")).isReachableProtocolAssignment()); try testing.expect(!(try parse("2001:1::")).isReachableProtocolAssignment()); // AMT, AS112-v6, ORCHIDv2 and the DRIP tags are blocks. try testing.expect((try parse("2001:3::1")).isReachableProtocolAssignment()); try testing.expect((try parse("2001:4:112::1")).isReachableProtocolAssignment()); try testing.expect(!(try parse("2001:4:113::1")).isReachableProtocolAssignment()); try testing.expect((try parse("2001:20::1")).isReachableProtocolAssignment()); try testing.expect((try parse("2001:30::1")).isReachableProtocolAssignment()); // Teredo and benchmarking are inside the /23 and are not reachable. try testing.expect(!(try parse("2001:0:1::1")).isReachableProtocolAssignment()); try testing.expect(!(try parse("2001:2::1")).isReachableProtocolAssignment()); } test embeddedIpv4 { // The low 32 bits read as an address, whether or not the address is one // that gives those bits that meaning. try testing.expect((try parse("::ffff:192.0.2.1")).embeddedIpv4().eql(try .parse("192.0.2.1"))); try testing.expect((try parse("2001:db8::1")).embeddedIpv4().eql(try .parse("0.0.0.1"))); }