// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A small command line front end to the z46 library: it validates and //! describes IP addresses, networks and interfaces given as arguments. const std = @import("std"); const Io = std.Io; const z46 = @import("z46"); const usage = \\usage: z46 [-q] ... \\ z46 --merge [-q] ... \\ \\Validates and describes IPv4 and IPv6 addresses, CIDR networks, the \\interfaces that carry an address on one of those networks, the ranges \\that CIDR cannot express, and endpoints that pair an address with a \\port. Text holding a '-' is read as a range ('10.0.0.10-10.0.0.20'); \\text holding a '/' is read as a network when its host bits are clear \\('192.168.1.0/24') and as an interface when they are not \\('192.168.1.42/24'); text carrying a port ('192.0.2.1:443', \\'[2001:db8::1]:443') is read as an endpoint, and everything else as an \\address. An address may be written in the square brackets a URL uses. \\Exits with status 1 if any argument is invalid. \\ \\With --merge, the arguments are folded instead of described: they are \\read as ranges of addresses, combined wherever they overlap or touch, \\and printed as the smallest set of CIDR networks that covers exactly \\the same addresses, which is the form a routing table or a firewall \\takes. A bare address counts as a single-address range and a network \\must have its host bits clear, as everywhere else here. The two \\versions fold separately; IPv4 is printed first. \\ \\ --merge fold the arguments together instead of describing them \\ -q, --quiet print nothing; report the result through the exit status \\ -h, --help print this help and exit \\ ; pub fn main(init: std.process.Init) !void { const arena = init.arena.allocator(); const io = init.io; const args = try init.minimal.args.toSlice(arena); var stdout_buffer: [4096]u8 = undefined; var stdout_file_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); const stdout = &stdout_file_writer.interface; var quiet = false; var merging = false; var inputs: std.ArrayList([]const u8) = .empty; for (args[@min(1, args.len)..]) |arg| { if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { try stdout.writeAll(usage); try stdout.flush(); return; } else if (std.mem.eql(u8, arg, "-q") or std.mem.eql(u8, arg, "--quiet")) { quiet = true; } else if (std.mem.eql(u8, arg, "--merge")) { merging = true; } else { try inputs.append(arena, arg); } } if (inputs.items.len == 0) { try stdout.writeAll(usage); try stdout.flush(); std.process.exit(2); } if (merging) { const failed = try mergeAll(arena, stdout, inputs.items, quiet); try stdout.flush(); if (failed) std.process.exit(1); return; } var failed = false; for (inputs.items, 0..) |input, i| { if (quiet) { if (!describes(input)) failed = true; continue; } if (i != 0) try stdout.writeByte('\n'); describe(stdout, input) catch |err| switch (err) { error.Invalid => failed = true, else => |e| return e, }; } try stdout.flush(); if (failed) std.process.exit(1); } /// Folds the arguments together and writes the covering networks, returning /// whether any argument was rejected. /// /// Everything is read as a range, since a range is the more general of the /// two shapes and folds the further: two networks that merely touch cannot be /// written as one network but are one range, and re-splitting that range into /// prefixes afterwards gives back a set no larger than merging as networks /// would have. So this is the tightest answer available, and it is printed as /// CIDR because that is what the thing at the other end takes. /// /// The storage is one allocation, which the merge sorts and folds in place; /// the library needs no allocator of its own for this. It is freed again /// rather than left to the caller's arena, so that this does not quietly /// depend on being called with one. fn mergeAll( gpa: std.mem.Allocator, w: *Io.Writer, inputs: []const []const u8, quiet: bool, ) !bool { const ranges = try gpa.alloc(z46.Range, inputs.len); defer gpa.free(ranges); var count: usize = 0; var failed = false; for (inputs) |input| { if (parseMergeable(input)) |range| { ranges[count] = range; count += 1; } else |err| { failed = true; if (!quiet) try w.print("{s}\n invalid: {s}\n", .{ input, @errorName(err) }); } } if (quiet) return failed; for (z46.Range.merge(ranges[0..count])) |range| { var it = range.prefixes(); while (it.next()) |network| try w.print("{f}\n", .{network}); } return failed; } /// Reads one argument of a `--merge` as a range: text holding a `-` as one /// directly, and everything else as a network, which covers a bare address /// since a network without a prefix is a single host. fn parseMergeable(input: []const u8) !z46.Range { if (std.mem.findScalar(u8, input, '-') != null) return z46.Range.parse(input); return .fromNetwork(try z46.Network.parse(input)); } /// Addresses may be written the way a URL writes them, so that a host copied /// out of one can be pasted straight in. const address_options: z46.Address.ParseOptions = .{ .allow_brackets = true }; /// `cidr` covers both `address/prefix` types, because punctuation cannot tell /// a network from an interface: which one `192.168.1.0/24` is meant to be is /// decided by whether its host bits are set, and only the parser knows that. const Kind = enum { address, cidr, range, endpoint }; /// Decides what a piece of text is meant to be from its punctuation alone, so /// that a mistake is reported against what the user was trying to write rather /// than against whichever type happened to parse it last. fn classify(input: []const u8) Kind { // A `-` appears in no other form, so it settles the question before the // rest of the punctuation is looked at. if (std.mem.findScalar(u8, input, '-') != null) return .range; if (std.mem.findScalar(u8, input, '/') != null) return .cidr; if (input.len != 0 and input[0] == '[') { // "[::1]:443" carries a port; "[::1]" is just a bracketed address. return if (std.mem.find(u8, input, "]:") != null) .endpoint else .address; } // One colon separates an IPv4 address from its port. More colons mean IPv6 // text, which cannot carry a port without brackets. return if (std.mem.count(u8, input, ":") == 1) .endpoint else .address; } fn describes(input: []const u8) bool { return switch (classify(input)) { // An interface accepts everything a network does and host bits // besides, so it is the more permissive of the two to validate with. .cidr => z46.Interface.isValid(input), .range => z46.Range.isValid(input), .endpoint => z46.Endpoint.isValid(input), .address => blk: { _ = z46.Address.parseWithOptions(input, address_options) catch break :blk false; break :blk true; }, }; } fn describe(w: *Io.Writer, input: []const u8) (Io.Writer.Error || error{Invalid})!void { try w.print("{s}\n", .{input}); switch (classify(input)) { .cidr => { const interface = z46.Interface.parse(input) catch |err| { try w.print(" invalid network or interface: {s}\n", .{@errorName(err)}); return error.Invalid; }; // Text a network would have accepted is described as one, so that // the two readings never disagree about the same input. if (interface.address().eql(interface.networkAddress())) { try describeNetwork(w, interface.network()); } else { try describeInterface(w, interface); } }, .range => { const range = z46.Range.parse(input) catch |err| { try w.print(" invalid range: {s}\n", .{@errorName(err)}); return error.Invalid; }; try describeRange(w, range); }, .endpoint => { const endpoint = z46.Endpoint.parse(input) catch |err| { try w.print(" invalid endpoint: {s}\n", .{@errorName(err)}); return error.Invalid; }; try describeEndpoint(w, endpoint); }, .address => { const address = z46.Address.parseWithOptions(input, address_options) catch |err| { try w.print(" invalid address: {s}\n", .{@errorName(err)}); // Saying only that the text is invalid is the least useful // true thing to say about `0x7f.0.0.1`. What matters is that // something else on the machine will accept it. if (z46.Ipv4Address.parseLegacy(input)) |legacy| { try w.print(" ambiguous a C library's inet_aton reads this as {f}\n", .{legacy}); } else |_| {} return error.Invalid; }; try describeAddress(w, address); }, } } fn describeAddress(w: *Io.Writer, address: z46.Address) Io.Writer.Error!void { try w.print(" family {s}\n", .{familyName(address.family())}); try w.print(" canonical {f}\n", .{address}); try describeAddressDetail(w, address); } fn describeEndpoint(w: *Io.Writer, endpoint: z46.Endpoint) Io.Writer.Error!void { const address = endpoint.address(); try w.print(" family {s}\n", .{familyName(endpoint.family())}); try w.print(" canonical {f}\n", .{endpoint}); try w.print(" address {f}\n", .{address}); try w.print(" port {d}\n", .{endpoint.port()}); try describeAddressDetail(w, address); } /// The part that reads the same whether the address arrived on its own or as /// half of an endpoint. fn describeAddressDetail(w: *Io.Writer, address: z46.Address) Io.Writer.Error!void { try w.print(" scope {f}\n", .{address.scope()}); // The name a PTR lookup for this address would ask about, which is the // one derived form nobody can write out reliably by hand. Straight to the // writer, since this output is already a stream and the name needs no // buffer of its own to reach it. try w.writeAll(" reverse "); try address.writeReverseName(w); try w.writeByte('\n'); switch (address) { .ipv4 => |v4| try w.print(" as IPv6 {f}\n", .{v4.toIpv6Mapped()}), .ipv6 => |v6| { // The fixed-width form, which is the one that lines up in a // column and sorts lexically. IPv4 has no separate expanded form. try w.print(" expanded {f}\n", .{std.fmt.alt(v6, .writeExpanded)}); if (v6.toIpv4Mapped()) |v4| try w.print(" as IPv4 {f}\n", .{v4}); }, } } /// A range is described by its two ends and then by the CIDR blocks it takes /// to cover it, which is the form a routing table or a firewall needs and the /// one nobody works out by hand. fn describeRange(w: *Io.Writer, range: z46.Range) Io.Writer.Error!void { try w.print(" family {s}\n", .{familyName(range.family())}); try w.print(" canonical {f}\n", .{range}); try w.print(" first {f}\n", .{range.first()}); try w.print(" last {f}\n", .{range.last()}); try w.print(" addresses {d}\n", .{range.addressCount()}); try w.writeAll(" networks "); var it = range.prefixes(); while (it.next()) |network| try w.print(" {f}", .{network}); try w.writeByte('\n'); } fn describeNetwork(w: *Io.Writer, network: z46.Network) Io.Writer.Error!void { try w.print(" family {s}\n", .{familyName(network.family())}); try w.print(" canonical {f}\n", .{network}); try describeNetworkDetail(w, network); } /// An interface is an address on a network, so it is described as both: the /// address, then everything the network it sits on would have said, then the /// classification of the address itself. fn describeInterface(w: *Io.Writer, interface: z46.Interface) Io.Writer.Error!void { const address = interface.address(); try w.print(" family {s}\n", .{familyName(interface.family())}); try w.print(" canonical {f}\n", .{interface}); try w.print(" address {f}\n", .{address}); try describeNetworkDetail(w, interface.network()); try describeAddressDetail(w, address); } /// The part that reads the same whether the network arrived on its own or as /// the network an interface sits on. fn describeNetworkDetail(w: *Io.Writer, network: z46.Network) Io.Writer.Error!void { try w.print(" network {f}\n", .{network.networkAddress()}); try w.print(" netmask {f}\n", .{network.netmask()}); try w.print(" hostmask {f}\n", .{network.hostmask()}); switch (network) { .ipv4 => |v4| { try w.print(" broadcast {f}\n", .{v4.broadcastAddress()}); try w.print(" hosts {f} - {f} ({d})\n", .{ v4.firstHost(), v4.lastHost(), v4.hostCount() }); }, .ipv6 => |v6| { try w.print(" last {f}\n", .{v6.lastAddress()}); try w.print(" hosts {f} - {f} ({d})\n", .{ v6.firstHost(), v6.lastHost(), v6.hostCount() }); try w.print(" addresses {d}\n", .{v6.addressCount()}); }, } } fn familyName(family: z46.Family) []const u8 { return switch (family) { .ipv4 => "IPv4", .ipv6 => "IPv6", }; } const testing = std.testing; test "describe an address" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "192.168.1.42"); try testing.expectEqualStrings( \\192.168.1.42 \\ family IPv4 \\ canonical 192.168.1.42 \\ scope private \\ reverse 42.1.168.192.in-addr.arpa \\ as IPv6 ::ffff:192.168.1.42 \\ , w.buffered()); } test "describe a network" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "192.168.1.0/24"); try testing.expectEqualStrings( \\192.168.1.0/24 \\ family IPv4 \\ canonical 192.168.1.0/24 \\ network 192.168.1.0 \\ netmask 255.255.255.0 \\ hostmask 0.0.0.255 \\ broadcast 192.168.1.255 \\ hosts 192.168.1.1 - 192.168.1.254 (254) \\ , w.buffered()); } test "describe an IPv6 network" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "2001:db8::/126"); try testing.expectEqualStrings( \\2001:db8::/126 \\ family IPv6 \\ canonical 2001:db8::/126 \\ network 2001:db8:: \\ netmask ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc \\ hostmask ::3 \\ last 2001:db8::3 \\ hosts 2001:db8::1 - 2001:db8::3 (3) \\ addresses 4 \\ , w.buffered()); } test "describe an interface" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "192.168.1.42/24"); try testing.expectEqualStrings( \\192.168.1.42/24 \\ family IPv4 \\ canonical 192.168.1.42/24 \\ address 192.168.1.42 \\ network 192.168.1.0 \\ netmask 255.255.255.0 \\ hostmask 0.0.0.255 \\ broadcast 192.168.1.255 \\ hosts 192.168.1.1 - 192.168.1.254 (254) \\ scope private \\ reverse 42.1.168.192.in-addr.arpa \\ as IPv6 ::ffff:192.168.1.42 \\ , w.buffered()); } test "describe an IPv6 interface" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "2001:db8::1/126"); try testing.expectEqualStrings( \\2001:db8::1/126 \\ family IPv6 \\ canonical 2001:db8::1/126 \\ address 2001:db8::1 \\ network 2001:db8:: \\ netmask ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc \\ hostmask ::3 \\ last 2001:db8::3 \\ hosts 2001:db8::1 - 2001:db8::3 (3) \\ addresses 4 \\ scope documentation \\ reverse 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa \\ expanded 2001:0db8:0000:0000:0000:0000:0000:0001 \\ , w.buffered()); } test "a network is still a network, host bits or none" { // The same text a network accepts is described as a network, so that the // two readings of `address/prefix` never disagree. A single host has no // host bits to set, and so is a network too. var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "192.0.2.1/32"); try testing.expectEqualStrings( \\192.0.2.1/32 \\ family IPv4 \\ canonical 192.0.2.1/32 \\ network 192.0.2.1 \\ netmask 255.255.255.255 \\ hostmask 0.0.0.0 \\ broadcast 192.0.2.1 \\ hosts 192.0.2.1 - 192.0.2.1 (1) \\ , w.buffered()); } test "a malformed prefix is reported against both readings" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try testing.expectError(error.Invalid, describe(&w, "192.168.1.42/33")); try testing.expectEqualStrings( \\192.168.1.42/33 \\ invalid network or interface: InvalidPrefixLength \\ , w.buffered()); } test "describe an endpoint" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "[2001:db8::1]:443"); try testing.expectEqualStrings( \\[2001:db8::1]:443 \\ family IPv6 \\ canonical [2001:db8::1]:443 \\ address 2001:db8::1 \\ port 443 \\ scope documentation \\ reverse 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa \\ expanded 2001:0db8:0000:0000:0000:0000:0000:0001 \\ , w.buffered()); } test "describe an IPv4 endpoint" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "192.0.2.1:80"); try testing.expectEqualStrings( \\192.0.2.1:80 \\ family IPv4 \\ canonical 192.0.2.1:80 \\ address 192.0.2.1 \\ port 80 \\ scope documentation \\ reverse 1.2.0.192.in-addr.arpa \\ as IPv6 ::ffff:192.0.2.1 \\ , w.buffered()); } test "a bracketed address without a port is still an address" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "[::1]"); try testing.expectEqualStrings( \\[::1] \\ family IPv6 \\ canonical ::1 \\ scope loopback \\ reverse 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 \\ expanded 0000:0000:0000:0000:0000:0000:0000:0001 \\ , w.buffered()); } test "describe a range" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "10.0.0.10-10.0.0.20"); try testing.expectEqualStrings( \\10.0.0.10-10.0.0.20 \\ family IPv4 \\ canonical 10.0.0.10-10.0.0.20 \\ first 10.0.0.10 \\ last 10.0.0.20 \\ addresses 11 \\ networks 10.0.0.10/31 10.0.0.12/30 10.0.0.16/30 10.0.0.20/32 \\ , w.buffered()); } test "describe a range that is a network" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "2001:db8::-2001:db8::ff"); // A range that lines up with a network needs only the one block. try testing.expect(std.mem.find( u8, w.buffered(), " networks 2001:db8::/120\n", ) != null); } test "text a C library would read differently is called out" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try testing.expectError(error.Invalid, describe(&w, "0x7f.0.0.1")); try testing.expectEqualStrings( \\0x7f.0.0.1 \\ invalid address: InvalidCharacter \\ ambiguous a C library's inet_aton reads this as 127.0.0.1 \\ , w.buffered()); // Text that is simply wrong gets no such line: nothing else would accept // it either. var other: [512]u8 = undefined; var w2: Io.Writer = .fixed(&other); try testing.expectError(error.Invalid, describe(&w2, "999.1.1.1")); try testing.expect(std.mem.find(u8, w2.buffered(), "ambiguous") == null); } test mergeAll { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); const failed = try mergeAll(testing.allocator, &w, &.{ "192.0.2.0/26", "192.0.2.64/26", "192.0.2.128/25", "10.0.0.5", "2001:db8::/33", "2001:db8:8000::/33", }, false); try testing.expect(!failed); // Each version folds on its own, IPv4 first, and a bare address is the // single-address network it stands for. try testing.expectEqualStrings( \\10.0.0.5/32 \\192.0.2.0/24 \\2001:db8::/32 \\ , w.buffered()); } test "merging folds ranges that touch, which networks cannot" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); // `10.0.0.10-10.0.0.20` and `10.0.0.21-10.0.0.30` are one run of // addresses, so they fold, and the run is then written as the blocks that // cover it. _ = try mergeAll(testing.allocator, &w, &.{ "10.0.0.10-10.0.0.20", "10.0.0.21-10.0.0.30", }, false); try testing.expectEqualStrings( \\10.0.0.10/31 \\10.0.0.12/30 \\10.0.0.16/29 \\10.0.0.24/30 \\10.0.0.28/31 \\10.0.0.30/32 \\ , w.buffered()); } test "merging reports a bad argument and folds the rest" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); // Host bits are refused here as everywhere else, and one bad argument // does not stop the others being folded. const failed = try mergeAll(testing.allocator, &w, &.{ "192.0.2.0/24", "192.0.2.1/24", }, false); try testing.expect(failed); try testing.expectEqualStrings( \\192.0.2.1/24 \\ invalid: HasHostBits \\192.0.2.0/24 \\ , w.buffered()); // Quiet still validates, and writes nothing at all. var silent: [64]u8 = undefined; var q: Io.Writer = .fixed(&silent); try testing.expect(try mergeAll(testing.allocator, &q, &.{"nonsense"}, true)); try testing.expectEqualStrings("", q.buffered()); } test parseMergeable { // A `-` makes it a range; everything else is read as a network, which is // what lets a bare address through as a single host. try testing.expect((try parseMergeable("10.0.0.1-10.0.0.9")) .eql(try .parse("10.0.0.1-10.0.0.9"))); try testing.expect((try parseMergeable("192.0.2.0/24")) .eql(.fromNetwork(try .parse("192.0.2.0/24")))); try testing.expect((try parseMergeable("10.0.0.5")).isSingleAddress()); try testing.expectError(error.HasHostBits, parseMergeable("192.0.2.1/24")); } test "input is classified by its punctuation" { try testing.expectEqual(.range, classify("10.0.0.10-10.0.0.20")); try testing.expectEqual(.range, classify("2001:db8::-2001:db8::ff")); try testing.expectEqual(.address, classify("192.0.2.1")); try testing.expectEqual(.address, classify("2001:db8::1")); try testing.expectEqual(.address, classify("::1")); try testing.expectEqual(.address, classify("[2001:db8::1]")); try testing.expectEqual(.address, classify("")); try testing.expectEqual(.cidr, classify("10.0.0.0/8")); try testing.expectEqual(.cidr, classify("2001:db8::/32")); try testing.expectEqual(.cidr, classify("192.168.1.42/24")); try testing.expectEqual(.endpoint, classify("192.0.2.1:443")); try testing.expectEqual(.endpoint, classify("[2001:db8::1]:443")); // An unbracketed IPv6 address with a port is not something the CLI can // tell apart from an address, so it is read as an address and the address // parser explains what is wrong with it. try testing.expectEqual(.address, classify("2001:db8::1:443")); } test "endpoints are validated in quiet mode" { try testing.expect(describes("192.0.2.1:443")); try testing.expect(describes("[::1]:8080")); try testing.expect(describes("[::1]")); try testing.expect(!describes("192.0.2.1:99999")); try testing.expect(!describes("[::1]:")); try testing.expect(!describes("[::1")); } test "invalid input is reported and flagged" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try testing.expectError(error.Invalid, describe(&w, "192.168.1.256")); try testing.expectEqualStrings( \\192.168.1.256 \\ invalid address: OctetOutOfRange \\ , w.buffered()); try testing.expect(describes("::1")); try testing.expect(describes("10.0.0.0/8")); // Host bits make it an interface rather than an invalid network. try testing.expect(describes("10.0.0.1/8")); try testing.expect(describes("2001:db8::1/32")); try testing.expect(!describes("10.0.0.1/33")); try testing.expect(!describes("nonsense")); var port_w: Io.Writer = .fixed(&buffer); try testing.expectError(error.Invalid, describe(&port_w, "192.0.2.1:99999")); try testing.expectEqualStrings( \\192.0.2.1:99999 \\ invalid endpoint: PortOutOfRange \\ , port_w.buffered()); } test classify { // Punctuation alone, so that a mistake is reported against the type the // user was reaching for. try testing.expectEqual(.address, classify("192.0.2.1")); try testing.expectEqual(.address, classify("[2001:db8::1]")); try testing.expectEqual(.cidr, classify("192.168.1.0/24")); try testing.expectEqual(.endpoint, classify("192.0.2.1:443")); try testing.expectEqual(.endpoint, classify("[2001:db8::1]:443")); // More than one colon and no brackets is IPv6 text, which cannot carry a // port. try testing.expectEqual(.address, classify("2001:db8::1")); } test describes { try testing.expect(describes("192.0.2.1")); try testing.expect(describes("192.168.1.42/24")); try testing.expect(describes("[2001:db8::1]:443")); // Brackets are accepted around an address, as a URL writes it. try testing.expect(describes("[2001:db8::1]")); try testing.expect(!describes("192.0.2.256")); } test describe { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describe(&w, "127.0.0.1"); try testing.expectEqualStrings( \\127.0.0.1 \\ family IPv4 \\ canonical 127.0.0.1 \\ scope loopback \\ reverse 1.0.0.127.in-addr.arpa \\ as IPv6 ::ffff:127.0.0.1 \\ , w.buffered()); // Invalid text is reported against the reading its punctuation asked for. w = .fixed(&buffer); try testing.expectError(error.Invalid, describe(&w, "192.0.2.256")); try testing.expect(std.mem.find(u8, w.buffered(), "invalid address") != null); } test describeAddress { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describeAddress(&w, try .parse("2001:db8::1")); try testing.expect(std.mem.startsWith(u8, w.buffered(), " family IPv6\n")); try testing.expect(std.mem.find(u8, w.buffered(), " scope documentation\n") != null); } test describeEndpoint { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describeEndpoint(&w, try .parse("192.0.2.1:443")); // An endpoint says the same as its address, with the port added. try testing.expect(std.mem.find(u8, w.buffered(), " canonical 192.0.2.1:443\n") != null); try testing.expect(std.mem.find(u8, w.buffered(), " port 443\n") != null); } test describeAddressDetail { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); // The part that reads the same whether the address arrived on its own or // as half of an endpoint: no family or canonical line. try describeAddressDetail(&w, try .parse("127.0.0.1")); try testing.expectEqualStrings( \\ scope loopback \\ reverse 1.0.0.127.in-addr.arpa \\ as IPv6 ::ffff:127.0.0.1 \\ , w.buffered()); } test describeNetwork { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try describeNetwork(&w, try .parse("192.168.1.0/24")); try testing.expect(std.mem.find(u8, w.buffered(), " canonical 192.168.1.0/24\n") != null); try testing.expect(std.mem.find(u8, w.buffered(), " broadcast 192.168.1.255\n") != null); } test describeInterface { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); // An interface is described as both an address and the network it sits on. try describeInterface(&w, try .parse("192.168.1.42/24")); try testing.expect(std.mem.find(u8, w.buffered(), " address 192.168.1.42\n") != null); try testing.expect(std.mem.find(u8, w.buffered(), " network 192.168.1.0\n") != null); try testing.expect(std.mem.find(u8, w.buffered(), " scope private\n") != null); } test describeNetworkDetail { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); // The part that reads the same whether the network arrived on its own or // as the network an interface sits on. try describeNetworkDetail(&w, try .parse("192.168.1.0/30")); try testing.expectEqualStrings( \\ network 192.168.1.0 \\ netmask 255.255.255.252 \\ hostmask 0.0.0.3 \\ broadcast 192.168.1.3 \\ hosts 192.168.1.1 - 192.168.1.2 (2) \\ , w.buffered()); } test familyName { try testing.expectEqualStrings("IPv4", familyName(.ipv4)); try testing.expectEqualStrings("IPv6", familyName(.ipv6)); }