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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! z46 parses, validates, formats and classifies IPv4 and IPv6 addresses,//! CIDR networks, and the endpoints that pair an address with a port.//!//! Everything here is allocation-free and works at comptime as readily as at//! runtime. Parsing is strict: only the canonical text forms are accepted, so//! the shorthands that `inet_aton` allows (`127.1`, `0x7f.0.0.1`, octal//! octets) are all rejected, as is text with leading or trailing whitespace.//!//! ```//! const z46 = @import("z46");//!//! const network = try z46.Ipv4Network.parse("192.168.1.0/24");//! const address = try z46.Ipv4Address.parse("192.168.1.42");//! try std.testing.expect(network.contains(address));//! ```//!//! Use the version-specific types when the version is known, and `Address`,//! `Network`, `Interface` and `Endpoint` when it is not. Every type formats//! with the `{f}` specifier and provides `parse`, `isValid`, `eql`, `order`//! and `bufPrint`.//!//! A network and an interface are the same notation read two ways: a network//! is `192.168.1.0/24` and rejects host bits, while an interface is the//! `192.168.1.42/24` that is configured on a link and keeps them.//!//! The canonical repository is//! [git.jcollie.dev/jeff/z46](https://git.jcollie.dev/jeff/z46), which is//! where the tests and this documentation are built; the README names the//! Codeberg, Tangled and Radicle mirrors that carry the same history.
const std = @import("std");
/// A 32-bit IPv4 address.pub const Ipv4Address = @import("Ipv4Address.zig");/// A 128-bit IPv6 address.pub const Ipv6Address = @import("Ipv6Address.zig");/// An IPv4 network in CIDR notation.pub const Ipv4Network = @import("Ipv4Network.zig");/// An IPv6 network in CIDR notation.pub const Ipv6Network = @import("Ipv6Network.zig");/// An IPv4 address with the prefix length of its network.pub const Ipv4Interface = @import("Ipv4Interface.zig");/// An IPv6 address with the prefix length of its network.pub const Ipv6Interface = @import("Ipv6Interface.zig");/// An inclusive range of IPv4 addresses, which CIDR notation cannot express.pub const Ipv4Range = @import("Ipv4Range.zig");/// An inclusive range of IPv6 addresses, which CIDR notation cannot express.pub const Ipv6Range = @import("Ipv6Range.zig");/// An IPv4 address paired with a port.pub const Ipv4Endpoint = @import("Ipv4Endpoint.zig");/// An IPv6 address paired with a port.pub const Ipv6Endpoint = @import("Ipv6Endpoint.zig");
/// Which version of the Internet Protocol an address or network belongs to.pub const Family = @import("address.zig").Family;/// An address of either version.pub const Address = @import("address.zig").Address;/// A network of either version.pub const Network = @import("network.zig").Network;/// An address and prefix length of either version.pub const Interface = @import("interface.zig").Interface;/// An inclusive range of addresses of either version.pub const Range = @import("range.zig").Range;/// An address and port of either version.pub const Endpoint = @import("endpoint.zig").Endpoint;/// The single category an address falls into, as one mutually exclusive/// answer rather than a dozen predicates.pub const Scope = @import("scope.zig").Scope;
test { // Pull in the tests of every file that makes up the library. The socket // address functions are generic over the pointer they are handed, so // nothing analyses that file until something calls one, and its own tests // are what do. std.testing.refAllDecls(@This()); _ = @import("sockaddr.zig");}
const testing = std.testing;
test "addresses and networks work together" { const network = try Ipv4Network.parse("192.168.1.0/24"); try testing.expect(network.contains(try .parse("192.168.1.42"))); try testing.expect(!network.contains(try .parse("192.168.2.42")));
const v6 = try Ipv6Network.parse("2001:db8::/32"); try testing.expect(v6.contains(try .parse("2001:db8:dead:beef::1"))); try testing.expect(!v6.contains(try .parse("2001:db9::1")));}
test "the whole API is reachable through the version-agnostic types" { const address = try Address.parse("2001:db8::1"); const network = try Network.parse("2001:db8::/32"); try testing.expect(network.contains(address)); try testing.expectEqual(.ipv6, address.family()); try testing.expect(address.isDocumentation()); try testing.expectFmt("2001:db8::1 is inside 2001:db8::/32", "{f} is inside {f}", .{ address, network });}
test "parsing works at comptime" { const network = comptime Ipv4Network.parse("10.0.0.0/8") catch unreachable; const address = comptime Ipv4Address.parse("10.1.2.3") catch unreachable; comptime std.debug.assert(network.contains(address)); try testing.expectFmt("10.0.0.0/8", "{f}", .{network});}
test "walking a network's subnets and addresses" { var found: usize = 0; var subnets = try (try Ipv4Network.parse("192.0.2.0/24")).subnets(26); while (subnets.next()) |subnet| { var hosts = subnet.hosts(); while (hosts.next()) |_| found += 1; } // Four /26 subnets of 62 usable hosts each. try testing.expectEqual(@as(usize, 4 * 62), found);}
test "sorting a mixed list of addresses" { var addresses = [_]Address{ try .parse("2001:db8::1"), try .parse("192.0.2.1"), try .parse("::1"), try .parse("10.0.0.1"), }; std.mem.sort(Address, &addresses, {}, lessThan);
var buffer: [128]u8 = undefined; var w: std.Io.Writer = .fixed(&buffer); for (addresses, 0..) |address, i| { if (i != 0) try w.writeAll(" "); try w.print("{f}", .{address}); } try testing.expectEqualStrings("10.0.0.1 192.0.2.1 ::1 2001:db8::1", w.buffered());}
/// Orders addresses for `std.mem.sort`, which asks for a `lessThan` where the/// types provide the three-way `order`.fn lessThan(_: void, a: Address, b: Address) bool { return a.order(b) == .lt;}
test lessThan { try testing.expect(lessThan({}, try .parse("10.0.0.1"), try .parse("10.0.0.2"))); // Every IPv4 address sorts before every IPv6 one. try testing.expect(lessThan({}, try .parse("255.255.255.255"), try .parse("::"))); // Not a strict ordering failure: equal addresses are not less than one // another, which is what `std.mem.sort` requires of a comparator. try testing.expect(!lessThan({}, try .parse("::1"), try .parse("::1")));}
test "random addresses and networks survive a round trip through text" { // A fixed seed keeps this reproducible; `zig build test --fuzz` explores // the same properties from the other direction. var prng: std.Random.DefaultPrng = .init(0x2b7e151628aed2a6); const random = prng.random();
for (0..10_000) |_| { const v4: Ipv4Address = .fromInt(random.int(u32)); var v4_text: [Ipv4Address.max_text_len]u8 = undefined; try testing.expect(v4.eql(try .parse(try v4.bufPrint(&v4_text))));
const v6: Ipv6Address = .fromInt(random.int(u128)); var v6_text: [Ipv6Address.max_text_len]u8 = undefined; try testing.expect(v6.eql(try .parse(try v6.bufPrint(&v6_text))));
const net4 = try Ipv4Network.initTruncate(v4, random.uintAtMost(u8, Ipv4Address.bit_count)); var net4_text: [Ipv4Network.max_text_len]u8 = undefined; try testing.expect(net4.eql(try .parse(try net4.bufPrint(&net4_text)))); // Containment agrees with the numeric bounds of the network. try testing.expect(net4.contains(v4)); try testing.expectEqual( net4.addressCount(), @as(u64, net4.broadcastAddress().toInt()) - net4.networkAddress().toInt() + 1, );
const if4 = try Ipv4Interface.init(v4, net4.prefix_len); var if4_text: [Ipv4Interface.max_text_len]u8 = undefined; try testing.expect(if4.eql(try .parse(try if4.bufPrint(&if4_text)))); // The host bits survive, and the network is the truncation of them. try testing.expect(if4.address.eql(v4)); try testing.expect(if4.network().eql(net4));
const net6 = try Ipv6Network.initTruncate(v6, random.uintAtMost(u8, Ipv6Address.bit_count)); var net6_text: [Ipv6Network.max_text_len]u8 = undefined; try testing.expect(net6.eql(try .parse(try net6.bufPrint(&net6_text)))); try testing.expect(net6.contains(v6)); try testing.expectEqual( net6.addressCount(), @as(u129, net6.lastAddress().toInt()) - net6.networkAddress().toInt() + 1, );
const if6 = try Ipv6Interface.init(v6, net6.prefix_len); var if6_text: [Ipv6Interface.max_text_len]u8 = undefined; try testing.expect(if6.eql(try .parse(try if6.bufPrint(&if6_text)))); try testing.expect(if6.address.eql(v6)); try testing.expect(if6.network().eql(net6)); }}
test "merging networks preserves exactly the addresses they covered" { // `merge` is the one operation here whose answer is not obvious by // inspection, so it is checked against the only thing that is: a bitmap // of every address covered, built one address at a time. The space is // `192.0.2.0/24`, small enough to enumerate and wide enough that random // subnets of it overlap, nest and sit next to each other. var prng = std.Random.DefaultPrng.init(0x2b1e_7a9c); const random = prng.random(); const base = (try Ipv4Address.parse("192.0.2.0")).toInt();
for (0..2000) |_| { var input: [8]Ipv4Network = undefined; var before: [256]bool = @splat(false);
const count = 1 + random.uintLessThan(usize, input.len); for (input[0..count]) |*network| { // Between a /24 and a /32 of the block, anywhere in it. const prefix_len = 24 + random.uintAtMost(u8, 8); const address: Ipv4Address = .fromInt(base + random.int(u8)); network.* = Ipv4Network.initTruncate(address, prefix_len) catch unreachable; var it = network.addresses(); while (it.next()) |covered| before[@intCast(covered.toInt() - base)] = true; }
const merged = Ipv4Network.merge(input[0..count]);
var after: [256]bool = @splat(false); for (merged) |network| { var it = network.addresses(); while (it.next()) |covered| after[@intCast(covered.toInt() - base)] = true; } try testing.expectEqualSlices(bool, &before, &after);
// And the result is minimal: sorted, with no network containing, // touching as a sibling, or duplicating the one after it. Either // would mean a fold was missed. for (merged[0..merged.len -| 1], merged[1..]) |a, b| { try testing.expectEqual(.lt, a.order(b)); try testing.expect(!a.containsNetwork(b)); try testing.expect(!a.overlaps(b)); try testing.expectEqual(null, Ipv4Network.join(a, b)); } }}
test "an interface keeps the host bits a network rejects" { // The same text, read two ways: an interface is the address configured on // a link, and the network is what that address sits on. const eth0 = try Interface.parse("192.168.1.42/24"); try testing.expectFmt("192.168.1.42/24", "{f}", .{eth0}); try testing.expectFmt("192.168.1.0/24", "{f}", .{eth0.network()}); try testing.expectError(error.HasHostBits, Network.parse("192.168.1.42/24"));
// The address half is the same value the address parser produces, so // everything that takes an address takes it. try testing.expect(eth0.address().isPrivate()); try testing.expect(eth0.network().contains(eth0.address())); try testing.expect((try Network.parse("192.168.0.0/16")).containsNetwork(eth0.network()));
// Truncating a network throws the host away; an interface is how it is // kept. try testing.expect((try Network.parseTruncate("192.168.1.42/24")).eql(eth0.network())); try testing.expect((try Ipv4Interface.parse("192.168.1.42/24")).eql(eth0.ipv4));}
test "endpoints pair an address with a port" { const endpoint = try Endpoint.parse("[2001:db8::1]:443"); try testing.expect(endpoint.address().eql(try .parse("2001:db8::1"))); try testing.expectEqual(@as(u16, 443), endpoint.port()); // The address half is the same value the address parser produces, so a // network can be asked about it directly. try testing.expect((try Network.parse("2001:db8::/32")).contains(endpoint.address())); try testing.expectFmt("192.0.2.1:80", "{f}", .{try Endpoint.parse("192.0.2.1:80")});}
test "random endpoints survive a round trip through text" { var prng: std.Random.DefaultPrng = .init(0x3243f6a8885a308d); const random = prng.random();
for (0..10_000) |_| { const port = random.int(u16);
const v4: Ipv4Endpoint = .init(.fromInt(random.int(u32)), port); var v4_text: [Ipv4Endpoint.max_text_len]u8 = undefined; try testing.expect(v4.eql(try .parse(try v4.bufPrint(&v4_text))));
const v6: Ipv6Endpoint = .init(.fromInt(random.int(u128)), port); var v6_text: [Ipv6Endpoint.max_text_len]u8 = undefined; try testing.expect(v6.eql(try .parse(try v6.bufPrint(&v6_text)))); }}
test "a configuration file reads straight into these types" { // The end-to-end path through `std.json`, which the per-type // `jsonParse` tests deliberately do not take: `parseFromSlice` builds a // parser by reflecting over the whole struct, and instantiating that once // per type is what a test binary cannot afford. Once, here, is plenty -- // it is the same machinery whichever type it is pointed at. const Config = struct { listen: Endpoint, allow: []const Network, pool: Range, };
const text = \\{ \\ "listen": "[2001:db8::1]:443", \\ "allow": ["10.0.0.0/8", "2001:db8::/32"], \\ "pool": "10.0.0.10-10.0.0.20" \\} ;
const parsed = try std.json.parseFromSlice(Config, testing.allocator, text, .{}); defer parsed.deinit();
try testing.expectEqual(@as(u16, 443), parsed.value.listen.port()); try testing.expect(parsed.value.allow[0].contains(try .parse("10.1.2.3"))); try testing.expect(parsed.value.allow[1].contains(try .parse("2001:db8::dead"))); try testing.expectEqual(@as(u129, 11), parsed.value.pool.addressCount());
// And back out again, in the canonical form rather than whatever the file // happened to say. var buffer: [256]u8 = undefined; var w: std.Io.Writer = .fixed(&buffer); try std.json.Stringify.value(parsed.value.listen, .{}, &w); try testing.expectEqualStrings("\"[2001:db8::1]:443\"", w.buffered());
// A bad address in a configuration file is a bad configuration file. try testing.expectError(error.InvalidCharacter, std.json.parseFromSlice( Config, testing.allocator, \\{"listen": "[2001:db8::1]:443", "allow": ["192.168.01.0/24"], "pool": "10.0.0.1-10.0.0.2"} , .{}, ));}
test "interoperating with std.Io.net socket addresses" { const v4 = try Ipv4Address.parse("192.0.2.1"); const socket4 = v4.toStdAddress(443); try testing.expectEqual(@as(u16, 443), socket4.port); try testing.expectEqual(v4, Ipv4Address.fromStdAddress(socket4));
const v6 = try Ipv6Address.parse("2001:db8::1"); const socket6 = v6.toStdAddress(443); try testing.expectEqual(@as(u16, 443), socket6.port); try testing.expectEqual(v6, Ipv6Address.fromStdAddress(socket6));}
test fuzzAddress { // Once over the empty input under `zig build test`, and until interrupted // under `zig build test --fuzz`. try std.testing.fuzz({}, fuzzAddress, .{});}
/// Parsing arbitrary bytes must never crash, and whatever text does parse must/// survive a round trip through its canonical form.fn fuzzAddress(_: void, smith: *std.testing.Smith) !void { var buffer: [Address.max_text_len + 8]u8 = undefined; const text = buffer[0..smith.slice(&buffer)];
if (Address.parse(text)) |address| { var printed: [Address.max_text_len]u8 = undefined; const canonical = try address.bufPrint(&printed); try testing.expect(address.eql(try .parse(canonical))); } else |_| {}
if (Ipv6Address.parseZoned(text)) |zoned| { try testing.expect(zoned.zone == null or zoned.zone.?.len > 0); } else |_| {}}
test fuzzInterface { try std.testing.fuzz({}, fuzzInterface, .{});}
fn fuzzInterface(_: void, smith: *std.testing.Smith) !void { var buffer: [Interface.max_text_len + 8]u8 = undefined; const text = buffer[0..smith.slice(&buffer)];
if (Interface.parse(text)) |interface| { // Whatever parsed sits in the network it reports, and its canonical // text parses back to the same interface. try testing.expect(interface.network().contains(interface.address())); try testing.expect(interface.network().prefixLen() == interface.prefixLen()); var printed: [Interface.max_text_len]u8 = undefined; const canonical = try interface.bufPrint(&printed); try testing.expect(interface.eql(try .parse(canonical))); } else |_| {}}
test fuzzNetwork { try std.testing.fuzz({}, fuzzNetwork, .{});}
fn fuzzNetwork(_: void, smith: *std.testing.Smith) !void { var buffer: [Network.max_text_len + 8]u8 = undefined; const text = buffer[0..smith.slice(&buffer)];
if (Network.parseTruncate(text)) |network| { // A truncated network always holds its own address, and its canonical // text parses back to the same network. try testing.expect(network.contains(network.networkAddress())); try testing.expect(network.contains(network.lastAddress())); var printed: [Network.max_text_len]u8 = undefined; const canonical = try network.bufPrint(&printed); try testing.expect(network.eql(try .parse(canonical))); } else |_| {}}