Something went wrong. Try again.
An allocation-free Zig library for parsing, validating, formatting and classifying IPv4 and IPv6 addresses, networks, ranges and endpoints.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An IP address of either version.
const std = @import("std");const json = @import("json.zig");const Writer = std.Io.Writer;
const Ipv4Address = @import("Ipv4Address.zig");const Ipv6Address = @import("Ipv6Address.zig");const sockaddr = @import("sockaddr.zig");const Scope = @import("scope.zig").Scope;
/// Which version of the Internet Protocol an address or network belongs to.pub const Family = enum { ipv4, ipv6,
/// Width of an address of this family in bits. pub fn bitCount(family: Family) u8 { return switch (family) { .ipv4 => Ipv4Address.bit_count, .ipv6 => Ipv6Address.bit_count, }; }
test bitCount { try testing.expectEqual(@as(u8, 32), Family.ipv4.bitCount()); try testing.expectEqual(@as(u8, 128), Family.ipv6.bitCount()); // Which is also the longest prefix a network of that family can have. try testing.expectEqual(@as(u8, 128), (try Address.parse("::1")).family().bitCount()); }};
/// An IPv4 or IPv6 address, for code that handles both without caring which it/// has.pub const Address = union(Family) { ipv4: Ipv4Address, ipv6: Ipv6Address,
pub const unspecified_ipv4: Address = .{ .ipv4 = .unspecified }; pub const unspecified_ipv6: Address = .{ .ipv6 = .unspecified }; pub const loopback_ipv4: Address = .{ .ipv4 = .loopback }; pub const loopback_ipv6: Address = .{ .ipv6 = .loopback };
pub const ParseError = Ipv4Address.ParseError || Ipv6Address.ParseError;
/// Options accepted by `parseWithOptions`. Only the IPv6 text form has /// anything to relax, so these are `Ipv6Address.ParseOptions`. pub const ParseOptions = Ipv6Address.ParseOptions;
/// Parses an address of either version. Text holding a `:` is read as /// IPv6 and everything else as IPv4, so the error returned is always the /// one from the version the text was reaching for. /// /// Square brackets are rejected; use `parseWithOptions` to accept them. pub fn parse(text: []const u8) ParseError!Address { return parseWithOptions(text, .{}); }
/// Like `parse`, but with the relaxations in `options` applied to IPv6 /// text, which is what makes a URL authority parseable: /// /// ``` /// const address = try Address.parseWithOptions(host, .{ .allow_brackets = true }); /// ``` /// /// Bracketed text is always read as IPv6. A URL wraps an IPv6 literal in /// brackets and writes an IPv4 address bare (RFC 3986), so `[1.2.3.4]` is /// a malformed IPv6 literal rather than an IPv4 address. pub fn parseWithOptions(text: []const u8, options: ParseOptions) ParseError!Address { const bracketed = options.allow_brackets and text.len != 0 and (text[0] == '[' or text[text.len - 1] == ']'); if (bracketed or std.mem.findScalar(u8, text, ':') != null) { return .{ .ipv6 = try .parseWithOptions(text, options) }; } return .{ .ipv4 = try .parse(text) }; }
/// Whether `text` is a valid address of either version, discarding the /// reason when it is not. Parsed with the default options, so square /// brackets are not accepted. pub fn isValid(text: []const u8) bool { _ = parse(text) catch return false; return true; }
pub fn family(a: Address) Family { return a; }
/// The address as an IPv6 address: IPv4 addresses become their /// IPv4-mapped form, `::ffff:a.b.c.d`. pub fn toIpv6(a: Address) Ipv6Address { return switch (a) { .ipv4 => |v4| v4.toIpv6Mapped(), .ipv6 => |v6| v6, }; }
/// The address as an IPv4 address, unwrapping an IPv4-mapped IPv6 address, /// or null when it is some other IPv6 address. pub fn toIpv4(a: Address) ?Ipv4Address { return switch (a) { .ipv4 => |v4| v4, .ipv6 => |v6| v6.toIpv4Mapped(), }; }
/// The longest text an address of either version can format to. pub const max_text_len = @max(Ipv4Address.max_text_len, Ipv6Address.max_text_len);
/// Writes the address in its canonical form for its version. Use the `{f}` /// specifier. pub fn format(a: Address, w: *Writer) Writer.Error!void { switch (a) { inline else => |address| try address.format(w), } }
/// Formats into `buffer`, returning the written slice. The buffer must be /// at least `max_text_len` bytes. pub fn bufPrint(a: Address, buffer: []u8) error{NoSpaceLeft}![]u8 { var w: Writer = .fixed(buffer); a.format(&w) catch return error.NoSpaceLeft; return w.buffered(); }
/// The longest the expanded form can be for either version, which is the /// IPv6 one. pub const max_expanded_len = @max(Ipv4Address.max_text_len, Ipv6Address.max_expanded_len);
/// Writes the address in the fixed-width form described by /// `Ipv6Address.writeExpanded`, which is what makes a column of addresses /// line up and sort lexically. /// /// IPv4 has no separate expanded form: its canonical text is already /// fixed in structure, and padding the octets would produce the leading /// zeros this library refuses to parse. So an IPv4 address is written /// exactly as `format` writes it, which is what Python's `ipaddress` also /// does for its `exploded` attribute. pub fn writeExpanded(a: Address, w: *Writer) Writer.Error!void { switch (a) { .ipv4 => |ipv4| try ipv4.format(w), .ipv6 => |ipv6| try ipv6.writeExpanded(w), } }
/// The expanded form written into `buffer`, returning the written slice. /// The buffer must be at least `max_expanded_len` bytes. pub fn expanded(a: Address, buffer: []u8) error{NoSpaceLeft}![]u8 { var w: Writer = .fixed(buffer); a.writeExpanded(&w) catch return error.NoSpaceLeft; return w.buffered(); }
/// The longest a reverse-DNS name can be for either version. pub const max_reverse_name_len = @max( Ipv4Address.max_reverse_name_len, Ipv6Address.max_reverse_name_len, );
/// Writes the name this address is looked up under in the reverse DNS, /// under `in-addr.arpa` or `ip6.arpa` as the version decides. pub fn reverseName(a: Address, buffer: []u8) error{NoSpaceLeft}![]u8 { return switch (a) { .ipv4 => |ipv4| ipv4.reverseName(buffer), .ipv6 => |ipv6| ipv6.reverseName(buffer), }; }
/// Writes the name this address is looked up under in the reverse DNS to /// `w`, for a caller that is writing a stream rather than filling a /// buffer. pub fn writeReverseName(a: Address, w: *Writer) Writer.Error!void { switch (a) { inline else => |address| try address.writeReverseName(w), } }
/// The next address, or null at the top of the address space of whichever /// version this is. The version never changes: the address after /// `255.255.255.255` is not `::`, it is nothing. pub fn next(a: Address) ?Address { return a.add(1); }
/// The previous address, or null at the bottom of the address space. pub fn prev(a: Address) ?Address { return a.sub(1); }
/// The address `delta` further up, or null when that would run off the top /// of the address space. `delta` is 128 bits wide so that it covers either /// version; one too large for an IPv4 address to hold is not an error but /// simply an overflow, and yields null. pub fn add(a: Address, delta: u128) ?Address { return switch (a) { .ipv4 => |v4| { const small = std.math.cast(u32, delta) orelse return null; return if (v4.add(small)) |sum| .{ .ipv4 = sum } else null; }, .ipv6 => |v6| if (v6.add(delta)) |sum| .{ .ipv6 = sum } else null, }; }
/// The address `delta` further down, or null when that would run off the /// bottom of the address space. pub fn sub(a: Address, delta: u128) ?Address { return switch (a) { .ipv4 => |v4| { const small = std.math.cast(u32, delta) orelse return null; return if (v4.sub(small)) |difference| .{ .ipv4 = difference } else null; }, .ipv6 => |v6| if (v6.sub(delta)) |difference| .{ .ipv6 = difference } else null, }; }
pub fn eql(a: Address, b: Address) bool { return switch (a) { .ipv4 => |v4| b == .ipv4 and v4.eql(b.ipv4), .ipv6 => |v6| b == .ipv6 and v6.eql(b.ipv6), }; }
/// Orders two addresses, with every IPv4 address before every IPv6 /// address. pub fn order(a: Address, b: Address) std.math.Order { return switch (a) { .ipv4 => |v4| switch (b) { .ipv4 => |other| v4.order(other), .ipv6 => .lt, }, .ipv6 => |v6| switch (b) { .ipv4 => .gt, .ipv6 => |other| v6.order(other), }, }; }
/// 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. /// They are ignored for an IPv4 address, which has no such fields. pub const SockaddrOptions = sockaddr.Options;
/// Fills in the socket address structure the version calls for, returning /// the number of bytes written: the `socklen_t` that goes with the /// pointer. /// /// The version is not known until run time, so the pointer has to be to /// something that can hold either: a `sockaddr` or a `sockaddr.storage`, /// from `std.posix`, `std.c` or `std.os.linux` alike. A pointer to a /// `sockaddr.in` or a `sockaddr.in6` has already settled the version, and /// is a compile error here; switch on the union and go through /// `Ipv4Address` or `Ipv6Address` to write into one of those. pub fn writeSockaddr(a: Address, port: u16, sa: anytype) u32 { return sockaddr.writeAddress(a, port, .{}, sa); }
/// Like `writeSockaddr`, but also setting the two fields that only an IPv6 /// structure has: the interface a link-local address is scoped to, and the /// flow label. Both are ignored for an IPv4 address. pub fn writeSockaddrWithOptions(a: Address, port: u16, sa: anytype, options: SockaddrOptions) u32 { return sockaddr.writeAddress(a, port, options, sa); }
/// Reads an address back out of a socket address structure of either /// version, dropping its port. /// /// A pointer to a `sockaddr.in` or a `sockaddr.in6` has already settled /// the version; a pointer to a `sockaddr` or a `sockaddr.storage` is read /// as whichever version its `family` names, and is /// `error.UnexpectedAddressFamily` when it names neither. pub fn fromSockaddr(sa: anytype) SockaddrError!Address { return sockaddr.readAddress(sa); }
// Classification shared by both versions. Predicates that exist for only // one version, such as `isBroadcast` or `multicastScope`, are reached // through the union payload.
pub fn isUnspecified(a: Address) bool { return switch (a) { inline else => |address| address.isUnspecified(), }; }
pub fn isLoopback(a: Address) bool { return switch (a) { inline else => |address| address.isLoopback(), }; }
pub fn isMulticast(a: Address) bool { return switch (a) { inline else => |address| address.isMulticast(), }; }
pub fn isLinkLocal(a: Address) bool { return switch (a) { inline else => |address| address.isLinkLocal(), }; }
pub fn isDocumentation(a: Address) bool { return switch (a) { inline else => |address| address.isDocumentation(), }; }
/// Whether the address is reserved for benchmarking: `198.18.0.0/15` /// (RFC 2544) or `2001:2::/48` (RFC 5180). pub fn isBenchmarking(a: Address) bool { return switch (a) { inline else => |address| address.isBenchmarking(), }; }
/// Whether the address is globally reachable. See `Ipv4Address.isGlobal` /// and `Ipv6Address.isGlobal` for what that means for each version. pub fn isGlobal(a: Address) bool { return switch (a) { inline else => |address| address.isGlobal(), }; }
/// The single category this address falls into. See `Scope`, and /// `Ipv4Address.scope` and `Ipv6Address.scope` for the cascade each /// version runs. pub fn scope(a: Address) Scope { return switch (a) { inline else => |address| address.scope(), }; }
/// Whether the address is one that hosts on a local network assign /// themselves or are assigned from private space: RFC 1918 space for IPv4 /// and unique local addresses for IPv6. pub fn isPrivate(a: Address) bool { return switch (a) { .ipv4 => |v4| v4.isPrivate(), .ipv6 => |v6| v6.isUniqueLocal(), }; }
/// Writes the value as a JSON string. See `json.stringify`. pub fn jsonStringify(value: Address, 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, ) !Address { _ = options; return json.parse(Address, allocator, source); }
test parse { try testing.expect((try Address.parse("192.0.2.1")) == .ipv4); try testing.expect((try Address.parse("2001:db8::1")) == .ipv6); // Text holding a `:` is read as IPv6, so the error reported is always // the one from the version the text was reaching for. try testing.expectError(error.OctetOutOfRange, Address.parse("192.0.2.256")); try testing.expectError(error.TooFewGroups, Address.parse("2001:db8")); // Brackets need `parseWithOptions`. try testing.expectError(error.InvalidCharacter, Address.parse("[2001:db8::1]")); }
test parseWithOptions { // A URL authority brackets an IPv6 literal and writes an IPv4 address // bare (RFC 3986). const host = try Address.parseWithOptions("[2001:db8::1]", .{ .allow_brackets = true }); try testing.expect(host.eql(try .parse("2001:db8::1"))); try testing.expect((try Address.parseWithOptions("192.0.2.1", .{ .allow_brackets = true })) == .ipv4); // Bracketed text is always IPv6, so a bracketed dotted quad is a // malformed IPv6 literal rather than an IPv4 address. try testing.expectError( error.TooFewGroups, Address.parseWithOptions("[192.0.2.1]", .{ .allow_brackets = true }), ); }
test isValid { try testing.expect(Address.isValid("192.0.2.1")); try testing.expect(Address.isValid("2001:db8::1")); try testing.expect(!Address.isValid("192.0.2.256")); // Parsed with the default options, so brackets are not accepted. try testing.expect(!Address.isValid("[2001:db8::1]")); }
test family { try testing.expectEqual(.ipv4, (try Address.parse("192.0.2.1")).family()); try testing.expectEqual(.ipv6, (try Address.parse("2001:db8::1")).family()); }
test toIpv6 { // An IPv4 address becomes its IPv4-mapped form, which is what a // dual-stack socket wants. try testing.expectFmt("::ffff:192.0.2.1", "{f}", .{(try Address.parse("192.0.2.1")).toIpv6()}); try testing.expectFmt("2001:db8::1", "{f}", .{(try Address.parse("2001:db8::1")).toIpv6()}); }
test toIpv4 { try testing.expect((try Address.parse("192.0.2.1")).toIpv4().?.eql(try .parse("192.0.2.1"))); // An IPv4-mapped address unwraps; any other IPv6 address does not. try testing.expect((try Address.parse("::ffff:192.0.2.1")).toIpv4().?.eql(try .parse("192.0.2.1"))); try testing.expectEqual(null, (try Address.parse("2001:db8::1")).toIpv4()); }
test jsonStringify { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try std.json.Stringify.value(try Address.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`. // `parseFromSlice` instantiates the whole of `std.json`'s reflection // machinery once per type, and fifteen copies of it in one test binary is // more than kcov will trace -- see the note on the coverage step in // `build.zig`. Going through the scanner tests the function this test 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 Address.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Address.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, Address.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, Address.jsonParse(testing.allocator, &number, .{}), ); }
test format { try testing.expectFmt("192.0.2.1", "{f}", .{try Address.parse("192.0.2.1")}); // Each version is written in its own canonical form. try testing.expectFmt("2001:db8::1", "{f}", .{try Address.parse("2001:0db8:0000::0001")}); }
test bufPrint { var buffer: [Address.max_text_len]u8 = undefined; try testing.expectEqualStrings("2001:db8::1", try (try Address.parse("2001:db8::1")).bufPrint(&buffer));
var small: [4]u8 = undefined; try testing.expectError(error.NoSpaceLeft, (try Address.parse("2001:db8::1")).bufPrint(&small)); }
test expanded { var buffer: [Address.max_expanded_len]u8 = undefined; try testing.expectEqualStrings( "2001:0db8:0000:0000:0000:0000:0000:0001", try (try Address.parse("2001:db8::1")).expanded(&buffer), ); // IPv4 has nothing to expand, so this is the canonical form. try testing.expectEqualStrings( "192.0.2.1", try (try Address.parse("192.0.2.1")).expanded(&buffer), ); }
test writeExpanded { var buffer: [64]u8 = undefined; var w: Writer = .fixed(&buffer); try (try Address.parse("::1")).writeExpanded(&w); try testing.expectEqualStrings("0000:0000:0000:0000:0000:0000:0000:0001", w.buffered()); }
test reverseName { var buffer: [Address.max_reverse_name_len]u8 = undefined; // Each version is looked up under its own zone. try testing.expectEqualStrings( "1.0.0.127.in-addr.arpa", try (try Address.parse("127.0.0.1")).reverseName(&buffer), ); try testing.expect(std.mem.endsWith( u8, try (try Address.parse("::1")).reverseName(&buffer), ".ip6.arpa", )); }
test writeReverseName { var buffer: [Address.max_reverse_name_len]u8 = undefined; var w: Writer = .fixed(&buffer); try (try Address.parse("10.2.0.52")).writeReverseName(&w); try testing.expectEqualStrings("52.0.2.10.in-addr.arpa", w.buffered()); }
test next { try testing.expect((try Address.parse("192.0.2.1")).next().? .eql(try .parse("192.0.2.2"))); try testing.expect((try Address.parse("2001:db8::1")).next().? .eql(try .parse("2001:db8::2"))); // The version is not a thing the address space wraps into. try testing.expectEqual(null, (try Address.parse("255.255.255.255")).next()); }
test prev { try testing.expect((try Address.parse("192.0.2.2")).prev().? .eql(try .parse("192.0.2.1"))); try testing.expectEqual(null, (try Address.parse("::")).prev()); }
test add { try testing.expect((try Address.parse("10.0.0.1")).add(255).? .eql(try .parse("10.0.1.0"))); // A delta too wide for IPv4 overflows rather than truncating. try testing.expectEqual(null, (try Address.parse("10.0.0.1")).add(1 << 40)); try testing.expect((try Address.parse("2001:db8::")).add(1 << 40).? .eql(try .parse("2001:db8::100:0:0"))); }
test sub { try testing.expect((try Address.parse("10.0.1.0")).sub(255).? .eql(try .parse("10.0.0.1"))); try testing.expectEqual(null, (try Address.parse("0.0.0.0")).sub(1)); }
test eql { try testing.expect((try Address.parse("2001:db8::1")).eql(try .parse("2001:0db8::1"))); // The two versions are never equal, however alike the text looks. try testing.expect(!(try Address.parse("192.0.2.1")).eql(try .parse("::ffff:192.0.2.1"))); }
test order { // Every IPv4 address sorts before every IPv6 address. try testing.expectEqual(.lt, (try Address.parse("255.255.255.255")).order(try .parse("::"))); try testing.expectEqual(.lt, (try Address.parse("10.0.0.1")).order(try .parse("10.0.0.2"))); try testing.expectEqual(.eq, (try Address.parse("::1")).order(try .parse("::1"))); }
test writeSockaddr { // The version is not known until run time, so the structure written // into has to be one that can hold either. var storage: std.posix.sockaddr.storage = undefined; const address = try Address.parse("2001:db8::1"); const len = address.writeSockaddr(443, &storage); try testing.expectEqual(@as(u32, @sizeOf(std.posix.sockaddr.in6)), len); try testing.expect(address.eql(try Address.fromSockaddr(&storage))); }
test writeSockaddrWithOptions { var storage: std.posix.sockaddr.storage = undefined; const address = try Address.parse("fe80::1"); _ = address.writeSockaddrWithOptions(22, &storage, .{ .scope_id = 2 }); try testing.expectEqual(@as(u32, 2), (try Ipv6Address.sockaddrOptions(&storage)).scope_id);
// Neither field exists on an IPv4 structure, so both are ignored there. const v4 = try Address.parse("192.0.2.1"); _ = v4.writeSockaddrWithOptions(443, &storage, .{ .scope_id = 2 }); try testing.expect(v4.eql(try Address.fromSockaddr(&storage))); }
test fromSockaddr { var storage: std.posix.sockaddr.storage = undefined; for ([_][]const u8{ "192.0.2.1", "2001:db8::1" }) |text| { const address = try Address.parse(text); _ = address.writeSockaddr(443, &storage); try testing.expect(address.eql(try Address.fromSockaddr(&storage))); }
// Any other family is reported rather than guessed at. storage.family = std.posix.AF.UNIX; try testing.expectError(error.UnexpectedAddressFamily, Address.fromSockaddr(&storage)); }
test isUnspecified { try testing.expect((try Address.parse("0.0.0.0")).isUnspecified()); try testing.expect((try Address.parse("::")).isUnspecified()); try testing.expect(!(try Address.parse("192.0.2.1")).isUnspecified()); }
test isLoopback { try testing.expect((try Address.parse("127.0.0.1")).isLoopback()); try testing.expect((try Address.parse("::1")).isLoopback()); try testing.expect(!(try Address.parse("192.0.2.1")).isLoopback()); }
test isMulticast { try testing.expect((try Address.parse("224.0.0.1")).isMulticast()); try testing.expect((try Address.parse("ff02::1")).isMulticast()); try testing.expect(!(try Address.parse("192.0.2.1")).isMulticast()); }
test isLinkLocal { try testing.expect((try Address.parse("169.254.1.1")).isLinkLocal()); try testing.expect((try Address.parse("fe80::1")).isLinkLocal()); try testing.expect(!(try Address.parse("192.0.2.1")).isLinkLocal()); }
test isDocumentation { try testing.expect((try Address.parse("192.0.2.1")).isDocumentation()); try testing.expect((try Address.parse("2001:db8::1")).isDocumentation()); try testing.expect(!(try Address.parse("1.1.1.1")).isDocumentation()); }
test isBenchmarking { try testing.expect((try Address.parse("198.18.0.1")).isBenchmarking()); try testing.expect((try Address.parse("2001:2::1")).isBenchmarking()); try testing.expect(!(try Address.parse("2001:db8::1")).isBenchmarking()); }
test isGlobal { try testing.expect((try Address.parse("1.1.1.1")).isGlobal()); try testing.expect((try Address.parse("2606:4700:4700::1111")).isGlobal()); try testing.expect(!(try Address.parse("10.0.0.1")).isGlobal()); try testing.expect(!(try Address.parse("fd00::1")).isGlobal()); }
test scope { try testing.expectEqual(.private, (try Address.parse("10.0.0.1")).scope()); try testing.expectEqual(.private, (try Address.parse("fd00::1")).scope()); try testing.expectEqual(.global, (try Address.parse("1.1.1.1")).scope()); // One call in place of a cascade of predicates in the right order. try testing.expectEqualStrings( "documentation", (try Address.parse("2001:db8::1")).scope().name(), ); }
test isPrivate { // RFC 1918 space for IPv4 and unique local addresses for IPv6, which // are the same idea under two names. try testing.expect((try Address.parse("192.168.1.1")).isPrivate()); try testing.expect((try Address.parse("fd00::1")).isPrivate()); try testing.expect(!(try Address.parse("1.1.1.1")).isPrivate()); }};
const testing = std.testing;
test "parse dispatches on version" { try testing.expect((try Address.parse("192.0.2.1")) == .ipv4); try testing.expect((try Address.parse("2001:db8::1")) == .ipv6); try testing.expect((try Address.parse("::ffff:192.0.2.1")) == .ipv6); try testing.expectEqual(.ipv4, (try Address.parse("192.0.2.1")).family());
// The error comes from the version the text was reaching for. try testing.expectError(error.OctetOutOfRange, Address.parse("256.0.0.1")); try testing.expectError(error.TooManyGroups, Address.parse("1:2:3:4:5:6:7:8:9")); try testing.expect(Address.isValid("::1")); try testing.expect(Address.isValid("127.0.0.1")); try testing.expect(!Address.isValid("not an address"));}
test "parsing a URL authority with brackets" { const brackets: Address.ParseOptions = .{ .allow_brackets = true };
// The bracketed form of a URL authority, and the bare forms alongside it. try testing.expect((try Address.parseWithOptions("[2001:db8::1]", brackets)) .eql(try Address.parse("2001:db8::1"))); try testing.expect((try Address.parseWithOptions("[::1]", brackets)) == .ipv6); try testing.expect((try Address.parseWithOptions("::1", brackets)) == .ipv6); try testing.expect((try Address.parseWithOptions("192.0.2.1", brackets)) == .ipv4);
// Brackets stay an error by default. try testing.expectError(error.InvalidCharacter, Address.parse("[::1]"));
// Bracketed text is IPv6 even when it holds a dotted quad, so this is a // malformed IPv6 literal rather than an IPv4 address. try testing.expectError(error.TooFewGroups, Address.parseWithOptions("[1.2.3.4]", brackets)); try testing.expect((try Address.parseWithOptions("[::ffff:1.2.3.4]", brackets)) == .ipv6);
// A bracket on one end only, wherever it is, is reported as such rather // than as a stray character from whichever version was guessed. try testing.expectError(error.UnmatchedBracket, Address.parseWithOptions("[::1", brackets)); try testing.expectError(error.UnmatchedBracket, Address.parseWithOptions("::1]", brackets)); try testing.expectError(error.UnmatchedBracket, Address.parseWithOptions("]", brackets)); try testing.expectError(error.UnmatchedBracket, Address.parseWithOptions("1.2.3.4]", brackets));
// A port is not part of an address. try testing.expectError(error.UnmatchedBracket, Address.parseWithOptions("[::1]:443", brackets));}
test "format" { try testing.expectFmt("192.0.2.1", "{f}", .{try Address.parse("192.0.2.1")}); try testing.expectFmt("2001:db8::1", "{f}", .{try Address.parse("2001:0db8::0001")});
var buffer: [Address.max_text_len]u8 = undefined; try testing.expectEqualStrings("::1", try (Address.loopback_ipv6).bufPrint(&buffer));}
test "conversion between versions" { const v4 = try Address.parse("192.0.2.1"); try testing.expectFmt("::ffff:192.0.2.1", "{f}", .{v4.toIpv6()}); try testing.expectEqual(Ipv4Address.init(192, 0, 2, 1), v4.toIpv4().?);
const mapped = try Address.parse("::ffff:192.0.2.1"); try testing.expectEqual(Ipv4Address.init(192, 0, 2, 1), mapped.toIpv4().?); try testing.expectEqual(null, (try Address.parse("2001:db8::1")).toIpv4());}
test "equality and ordering" { try testing.expect((try Address.parse("192.0.2.1")).eql(try Address.parse("192.0.2.1"))); try testing.expect(!(try Address.parse("192.0.2.1")).eql(try Address.parse("::ffff:192.0.2.1"))); try testing.expectEqual(.lt, (try Address.parse("255.255.255.255")).order(try Address.parse("::"))); try testing.expectEqual(.gt, (try Address.parse("::")).order(try Address.parse("0.0.0.0"))); try testing.expectEqual(.lt, (try Address.parse("192.0.2.1")).order(try Address.parse("192.0.2.2")));}
test "classification" { try testing.expect((try Address.parse("127.0.0.1")).isLoopback()); try testing.expect((try Address.parse("::1")).isLoopback()); try testing.expect((try Address.parse("192.168.1.1")).isPrivate()); try testing.expect((try Address.parse("fd00::1")).isPrivate()); try testing.expect((try Address.parse("fe80::1")).isLinkLocal()); try testing.expect((try Address.parse("169.254.1.1")).isLinkLocal()); try testing.expect((try Address.parse("224.0.0.1")).isMulticast()); try testing.expect((try Address.parse("ff02::1")).isMulticast()); try testing.expect((try Address.parse("8.8.8.8")).isGlobal()); try testing.expect((try Address.parse("2606:4700::1")).isGlobal()); try testing.expect(!(try Address.parse("10.0.0.1")).isGlobal()); try testing.expect((try Address.parse("2001:db8::1")).isDocumentation()); try testing.expect((try Address.parse("192.0.2.1")).isDocumentation());}
test "family bit counts" { try testing.expectEqual(@as(u8, 32), Family.ipv4.bitCount()); try testing.expectEqual(@as(u8, 128), Family.ipv6.bitCount());}
test "a reverse-DNS name goes under the suffix its version uses" { var buffer: [Address.max_reverse_name_len]u8 = undefined; try testing.expectEqualStrings( "3.2.0.192.in-addr.arpa", try (try Address.parse("192.0.2.3")).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 (try Address.parse("::1")).reverseName(&buffer), ); // An IPv4-mapped address is still an IPv6 address, and its reverse name // is the one that says so. A caller wanting the other has to ask for it. const mapped = try Address.parse("::ffff:192.0.2.3"); try testing.expect(std.mem.endsWith(u8, try mapped.reverseName(&buffer), ".ip6.arpa")); try testing.expectEqualStrings( "3.2.0.192.in-addr.arpa", try mapped.toIpv4().?.reverseName(&buffer), );}
test "a reverse-DNS name written to a writer dispatches on the version too" { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try (try Address.parse("192.0.2.3")).writeReverseName(&w); try testing.expectEqualStrings("3.2.0.192.in-addr.arpa", w.buffered());
w = .fixed(&buffer); try (try Address.parse("::1")).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(), );}