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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An address and the prefix length of its network, of either version.
const std = @import("std");const json = @import("json.zig");const Writer = std.Io.Writer;
const Address = @import("address.zig").Address;const Family = @import("address.zig").Family;const Ipv4Interface = @import("Ipv4Interface.zig");const Ipv6Interface = @import("Ipv6Interface.zig");const Network = @import("network.zig").Network;
/// An address with the prefix length of the network it sits on, of either/// version, for code that handles both without caring which it has.////// This is `Network`'s counterpart: a network is `192.168.1.0/24` and insists/// on it, an interface is the `192.168.1.42/24` an operating system configures/// on a link. `network()` goes from the second to the first.pub const Interface = union(Family) { ipv4: Ipv4Interface, ipv6: Ipv6Interface,
/// The IPv4 loopback interface as it is conventionally configured, /// `127.0.0.1/8`. pub const loopback_ipv4: Interface = .{ .ipv4 = .loopback }; /// The IPv6 loopback interface as it is conventionally configured, /// `::1/128`. pub const loopback_ipv6: Interface = .{ .ipv6 = .loopback };
pub const ParseError = Ipv4Interface.ParseError || Ipv6Interface.ParseError;
/// Parses an interface of either version. Text holding a `:` before the /// `/` is read as IPv6 and everything else as IPv4. /// /// Host bits are kept, which is the whole of the difference from /// `Network.parse`. pub fn parse(text: []const u8) ParseError!Interface { if (isIpv6Text(text)) return .{ .ipv6 = try .parse(text) }; return .{ .ipv4 = try .parse(text) }; }
fn isIpv6Text(text: []const u8) bool { const address_text = text[0 .. std.mem.findScalar(u8, text, '/') orelse text.len]; return std.mem.findScalar(u8, address_text, ':') != null; }
/// Whether `text` is a valid interface of either version, discarding the /// reason when it is not. pub fn isValid(text: []const u8) bool { _ = parse(text) catch return false; return true; }
/// Pairs an address with a prefix length, choosing the interface type to /// match. pub fn init(value: Address, prefix_len: u8) error{InvalidPrefixLength}!Interface { return switch (value) { .ipv4 => |v4| .{ .ipv4 = try .init(v4, prefix_len) }, .ipv6 => |v6| .{ .ipv6 = try .init(v6, prefix_len) }, }; }
/// The `/32` or `/128` interface holding `address` alone. pub fn fromAddress(value: Address) Interface { return switch (value) { .ipv4 => |v4| .{ .ipv4 = .fromAddress(v4) }, .ipv6 => |v6| .{ .ipv6 = .fromAddress(v6) }, }; }
pub fn family(i: Interface) Family { return i; }
/// The address, with its host bits intact. pub fn address(i: Interface) Address { return switch (i) { .ipv4 => |v4| .{ .ipv4 = v4.address }, .ipv6 => |v6| .{ .ipv6 = v6.address }, }; }
/// Length of the routing prefix in bits. pub fn prefixLen(i: Interface) u8 { return switch (i) { inline else => |interface| interface.prefix_len, }; }
/// The network the interface sits on, with the host bits cleared. pub fn network(i: Interface) Network { return switch (i) { .ipv4 => |v4| .{ .ipv4 = v4.network() }, .ipv6 => |v6| .{ .ipv6 = v6.network() }, }; }
pub fn netmask(i: Interface) Address { return switch (i) { .ipv4 => |v4| .{ .ipv4 = v4.netmask() }, .ipv6 => |v6| .{ .ipv6 = v6.netmask() }, }; }
pub fn hostmask(i: Interface) Address { return switch (i) { .ipv4 => |v4| .{ .ipv4 = v4.hostmask() }, .ipv6 => |v6| .{ .ipv6 = v6.hostmask() }, }; }
/// The network address of the network the interface sits on. pub fn networkAddress(i: Interface) Address { return switch (i) { .ipv4 => |v4| .{ .ipv4 = v4.networkAddress() }, .ipv6 => |v6| .{ .ipv6 = v6.networkAddress() }, }; }
/// The last address of the network the interface sits on: the broadcast /// address of an IPv4 network, and simply the highest address of an IPv6 /// one. pub fn lastAddress(i: Interface) Address { return switch (i) { .ipv4 => |v4| .{ .ipv4 = v4.broadcastAddress() }, .ipv6 => |v6| .{ .ipv6 = v6.lastAddress() }, }; }
/// The host bits on their own, as in `0.0.0.42` for `192.168.1.42/24`. pub fn hostBits(i: Interface) Address { return switch (i) { .ipv4 => |v4| .{ .ipv4 = v4.hostBits() }, .ipv6 => |v6| .{ .ipv6 = v6.hostBits() }, }; }
/// Whether the address is the network address of its own network, which /// IPv4 reserves and IPv6 uses as a link's subnet-router anycast address. pub fn isNetworkAddress(i: Interface) bool { return switch (i) { inline else => |interface| interface.isNetworkAddress(), }; }
/// Whether the address is one a host may be given. An IPv4 network /// reserves its broadcast address as well as its network address; IPv6 has /// no broadcast address to reserve. pub fn isHostAddress(i: Interface) bool { return switch (i) { inline else => |interface| interface.isHostAddress(), }; }
/// The longest text an interface of either version can format to. pub const max_text_len = @max(Ipv4Interface.max_text_len, Ipv6Interface.max_text_len);
/// Writes `address/prefix`. Use the `{f}` specifier. pub fn format(i: Interface, w: *Writer) Writer.Error!void { switch (i) { inline else => |interface| try interface.format(w), } }
/// Formats into `buffer`, returning the written slice. The buffer must be /// at least `max_text_len` bytes. pub fn bufPrint(i: Interface, buffer: []u8) error{NoSpaceLeft}![]u8 { var w: Writer = .fixed(buffer); i.format(&w) catch return error.NoSpaceLeft; return w.buffered(); }
pub fn eql(i: Interface, other: Interface) bool { return switch (i) { .ipv4 => |v4| other == .ipv4 and v4.eql(other.ipv4), .ipv6 => |v6| other == .ipv6 and v6.eql(other.ipv6), }; }
/// Orders two interfaces, with every IPv4 interface before every IPv6 one. pub fn order(i: Interface, other: Interface) std.math.Order { return switch (i) { .ipv4 => |v4| switch (other) { .ipv4 => |o| v4.order(o), .ipv6 => .lt, }, .ipv6 => |v6| switch (other) { .ipv4 => .gt, .ipv6 => |o| v6.order(o), }, }; }
/// Writes the value as a JSON string. See `json.stringify`. pub fn jsonStringify(value: Interface, 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, ) !Interface { _ = options; return json.parse(Interface, allocator, source); }
test parse { try testing.expect((try Interface.parse("192.168.1.42/24")) == .ipv4); try testing.expect((try Interface.parse("2001:db8::1/64")) == .ipv6); // Host bits are kept rather than rejected, which is the whole of the // difference from `Network.parse`. try testing.expectFmt("192.168.1.42/24", "{f}", .{try Interface.parse("192.168.1.42/24")}); }
test isValid { try testing.expect(Interface.isValid("192.168.1.42/24")); try testing.expect(Interface.isValid("2001:db8::1/64")); // A bare address is a `/32` or a `/128`, and so is valid. try testing.expect(Interface.isValid("192.0.2.1")); try testing.expect(!Interface.isValid("192.168.1.42/33")); }
test init { const eth0 = try Interface.init(try .parse("192.168.1.42"), 24); try testing.expect(eth0.eql(try Interface.parse("192.168.1.42/24"))); // The interface type follows the address's version. try testing.expect((try Interface.init(try .parse("2001:db8::1"), 64)) == .ipv6); try testing.expectError(error.InvalidPrefixLength, Interface.init(try .parse("192.0.2.1"), 33)); }
test fromAddress { const host = Interface.fromAddress(try .parse("192.0.2.1")); try testing.expectEqual(@as(u8, 32), host.prefixLen()); try testing.expectEqual(@as(u8, 128), Interface.fromAddress(try .parse("::1")).prefixLen()); }
test family { try testing.expectEqual(.ipv4, (try Interface.parse("192.168.1.42/24")).family()); try testing.expectEqual(.ipv6, (try Interface.parse("2001:db8::1/64")).family()); }
test address { const eth0 = try Interface.parse("192.168.1.42/24"); // The address keeps its host bits, and is the same value the address // parser produces. try testing.expect(eth0.address().eql(try .parse("192.168.1.42"))); try testing.expect(eth0.address().isPrivate()); }
test prefixLen { try testing.expectEqual(@as(u8, 24), (try Interface.parse("192.168.1.42/24")).prefixLen()); try testing.expectEqual(@as(u8, 64), (try Interface.parse("2001:db8::1/64")).prefixLen()); }
test network { const eth0 = try Interface.parse("192.168.1.42/24"); try testing.expect(eth0.network().eql(try .parse("192.168.1.0/24"))); try testing.expect(eth0.network().contains(eth0.address())); }
test netmask { try testing.expect((try Interface.parse("192.168.1.42/24")) .netmask().eql(try .parse("255.255.255.0"))); try testing.expect((try Interface.parse("2001:db8::1/64")) .netmask().eql(try .parse("ffff:ffff:ffff:ffff::"))); }
test hostmask { try testing.expect((try Interface.parse("192.168.1.42/24")) .hostmask().eql(try .parse("0.0.0.255"))); }
test networkAddress { try testing.expect((try Interface.parse("192.168.1.42/24")) .networkAddress().eql(try .parse("192.168.1.0"))); }
test lastAddress { // The broadcast address of an IPv4 network, and simply the highest // address of an IPv6 one. try testing.expect((try Interface.parse("192.168.1.42/24")) .lastAddress().eql(try .parse("192.168.1.255"))); try testing.expect((try Interface.parse("2001:db8::1/112")) .lastAddress().eql(try .parse("2001:db8::ffff"))); }
test hostBits { // The part of the address the network does not determine. try testing.expect((try Interface.parse("192.168.1.42/24")) .hostBits().eql(try .parse("0.0.0.42"))); try testing.expect((try Interface.parse("2001:db8::1/64")) .hostBits().eql(try .parse("::1"))); }
test isNetworkAddress { try testing.expect((try Interface.parse("192.168.1.0/24")).isNetworkAddress()); // IPv6 uses this one as the link's subnet-router anycast address. try testing.expect((try Interface.parse("2001:db8::/64")).isNetworkAddress()); try testing.expect(!(try Interface.parse("192.168.1.42/24")).isNetworkAddress()); }
test isHostAddress { try testing.expect((try Interface.parse("192.168.1.42/24")).isHostAddress()); try testing.expect(!(try Interface.parse("192.168.1.0/24")).isHostAddress()); // An IPv4 network reserves its broadcast address; IPv6 has none to // reserve, so the top of the network is usable. try testing.expect(!(try Interface.parse("192.168.1.255/24")).isHostAddress()); try testing.expect((try Interface.parse("2001:db8::ffff/112")).isHostAddress()); }
test jsonStringify { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try std.json.Stringify.value(try Interface.parse("192.0.2.1/24"), .{}, &w); // A JSON string holding exactly what `format` would have written. try testing.expectEqualStrings("\"192.0.2.1/24\"", 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, "\"192.0.2.1/24\""); defer scanner.deinit(); const value = try Interface.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Interface.parse("192.0.2.1/24")));
// 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, "\"192.0.2.1/33\""); defer bad.deinit(); try testing.expectError( error.InvalidCharacter, Interface.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, Interface.jsonParse(testing.allocator, &number, .{}), ); }
test format { try testing.expectFmt("192.168.1.42/24", "{f}", .{try Interface.parse("192.168.1.42/24")}); try testing.expectFmt("2001:db8::1/64", "{f}", .{try Interface.parse("2001:0db8::1/64")}); }
test bufPrint { var buffer: [Interface.max_text_len]u8 = undefined; try testing.expectEqualStrings( "2001:db8::1/64", try (try Interface.parse("2001:db8::1/64")).bufPrint(&buffer), );
var small: [4]u8 = undefined; try testing.expectError(error.NoSpaceLeft, (try Interface.parse("2001:db8::1/64")).bufPrint(&small)); }
test eql { try testing.expect((try Interface.parse("2001:db8::1/64")) .eql(try Interface.parse("2001:0db8::1/64"))); // The two versions are never equal, and the prefix length is part of // the interface. try testing.expect(!(try Interface.parse("192.168.1.42/24")) .eql(try Interface.parse("192.168.1.42/16"))); }
test order { // Every IPv4 interface sorts before every IPv6 one, and two at the // same address sort with the wider network first. try testing.expectEqual(.lt, (try Interface.parse("255.255.255.255/32")) .order(try Interface.parse("::/0"))); try testing.expectEqual(.lt, (try Interface.parse("192.168.1.42/16")) .order(try Interface.parse("192.168.1.42/24"))); try testing.expectEqual(.eq, (try Interface.parse("::1/128")) .order(try Interface.parse("::1/128"))); }
test isIpv6Text { // A `:` before the `/` is what marks the text as IPv6; anything after // the slash is a prefix length and says nothing about the version. try testing.expect(isIpv6Text("2001:db8::/32")); try testing.expect(isIpv6Text("::1")); try testing.expect(!isIpv6Text("192.168.1.0/24")); try testing.expect(!isIpv6Text("192.0.2.1")); }};
const testing = std.testing;
test "parse dispatches on version" { try testing.expect((try Interface.parse("192.168.1.42/24")) == .ipv4); try testing.expect((try Interface.parse("2001:db8::1/64")) == .ipv6); try testing.expect((try Interface.parse("::1/128")) == .ipv6); try testing.expect((try Interface.parse("10.0.0.1/255.0.0.0")) == .ipv4); try testing.expectEqual(.ipv6, (try Interface.parse("2001:db8::1/64")).family());
// The host bits a network rejects are exactly what this type is for. try testing.expect(Interface.isValid("192.168.1.42/24")); try testing.expect(Interface.isValid("2001:db8::1/32")); try testing.expect(!Network.isValid("192.168.1.42/24")); try testing.expect(!Network.isValid("2001:db8::1/32"));
try testing.expectError(error.InvalidPrefixLength, Interface.parse("192.168.1.42/33")); try testing.expectError(error.InvalidPrefixLength, Interface.parse("2001:db8::1/129")); try testing.expectError(error.InvalidPrefix, Interface.parse("192.168.1.42/")); try testing.expect(!Interface.isValid("nonsense"));}
test "building from an address" { try testing.expect((try Interface.init(try .parse("192.168.1.42"), 24)) .eql(try Interface.parse("192.168.1.42/24"))); try testing.expect((try Interface.init(try .parse("2001:db8::1"), 64)) .eql(try Interface.parse("2001:db8::1/64"))); try testing.expectError(error.InvalidPrefixLength, Interface.init(try .parse("192.168.1.42"), 33)); try testing.expectError(error.InvalidPrefixLength, Interface.init(try .parse("2001:db8::1"), 129));
try testing.expect(Interface.fromAddress(try .parse("192.0.2.1")).eql(try Interface.parse("192.0.2.1/32"))); try testing.expect(Interface.fromAddress(try .parse("::1")).eql(Interface.loopback_ipv6)); try testing.expect(Interface.loopback_ipv4.eql(try Interface.parse("127.0.0.1/8")));}
test "properties" { const v4 = try Interface.parse("192.168.1.42/24"); try testing.expectEqual(@as(u8, 24), v4.prefixLen()); try testing.expectFmt("192.168.1.42", "{f}", .{v4.address()}); try testing.expectFmt("192.168.1.0/24", "{f}", .{v4.network()}); try testing.expectFmt("192.168.1.0", "{f}", .{v4.networkAddress()}); try testing.expectFmt("192.168.1.255", "{f}", .{v4.lastAddress()}); try testing.expectFmt("255.255.255.0", "{f}", .{v4.netmask()}); try testing.expectFmt("0.0.0.255", "{f}", .{v4.hostmask()}); try testing.expectFmt("0.0.0.42", "{f}", .{v4.hostBits()}); try testing.expect(v4.isHostAddress()); try testing.expect(!v4.isNetworkAddress());
const v6 = try Interface.parse("2001:db8::1/64"); try testing.expectEqual(@as(u8, 64), v6.prefixLen()); try testing.expectFmt("2001:db8::1", "{f}", .{v6.address()}); try testing.expectFmt("2001:db8::/64", "{f}", .{v6.network()}); try testing.expectFmt("2001:db8::ffff:ffff:ffff:ffff", "{f}", .{v6.lastAddress()}); try testing.expectFmt("::1", "{f}", .{v6.hostBits()});
// An IPv4 network reserves the top of its range and an IPv6 one does not. try testing.expect(!(try Interface.parse("192.168.1.255/24")).isHostAddress()); try testing.expect((try Interface.parse("2001:db8::ffff:ffff:ffff:ffff/64")).isHostAddress()); try testing.expect((try Interface.parse("192.168.1.0/24")).isNetworkAddress()); try testing.expect((try Interface.parse("2001:db8::/64")).isNetworkAddress());}
test "the network an interface sits on answers questions about it" { const i = try Interface.parse("192.168.1.42/24"); try testing.expect(i.network().contains(i.address())); try testing.expect(!i.network().contains(try .parse("192.168.2.42"))); try testing.expectEqual(@as(u129, 256), i.network().addressCount());}
test "format and ordering" { try testing.expectFmt("192.168.1.42/24", "{f}", .{try Interface.parse("192.168.1.42/24")}); try testing.expectFmt("2001:db8::1/64", "{f}", .{try Interface.parse("2001:db8::1/64")});
var buffer: [Interface.max_text_len]u8 = undefined; try testing.expectEqualStrings("::1/128", try Interface.loopback_ipv6.bufPrint(&buffer));
try testing.expectEqual(.lt, (try Interface.parse("255.0.0.1/8")).order(try Interface.parse("::1/128"))); try testing.expectEqual(.gt, (try Interface.parse("::1/128")).order(try Interface.parse("255.0.0.1/8"))); try testing.expectEqual(.lt, (try Interface.parse("10.0.0.1/8")).order(try Interface.parse("10.0.0.1/16"))); try testing.expectEqual(.eq, (try Interface.parse("10.0.0.1/8")).order(try Interface.parse("10.0.0.1/8")));
// Equality never crosses versions, even for the mapped form of the same // address. try testing.expect(!(try Interface.parse("192.0.2.1/32")).eql(try Interface.parse("::ffff:192.0.2.1/128")));}