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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An IPv6 address together with the prefix length of the network it sits on,//! as in `2001:db8::1/64`: what is configured on an interface, and what//! `ip addr` prints.//!//! This is the counterpart of `Ipv6Network`, which stores a network and//! insists that its host bits be clear. An interface is the same notation read//! the other way round: the address is kept exactly as written, host bits and//! all, and `network()` hands back the network it belongs to.//!//! ```//! const eth0 = try Ipv6Interface.parse("2001:db8::1/64");//! // 2001:db8::1 on 2001:db8::/64//! ```
const std = @import("std");const json = @import("json.zig");const Writer = std.Io.Writer;
const decimal = @import("decimal.zig");const Ipv6Address = @import("Ipv6Address.zig");const Ipv6Network = @import("Ipv6Network.zig");
const Ipv6Interface = @This();
/// The address, with whatever host bits it was given.address: Ipv6Address,/// Length of the routing prefix in bits, at most 128. `init` and `parse`/// maintain that bound, and the rest of this file relies on it.prefix_len: u8,
/// The loopback interface as it is conventionally configured, `::1/128`.pub const loopback: Ipv6Interface = .{ .address = .loopback, .prefix_len = Ipv6Address.bit_count };
pub const InitError = error{ /// The prefix length was greater than 128. InvalidPrefixLength,};
/// Builds an interface. Unlike `Ipv6Network.init`, the host bits of `address`/// may be anything, so there is no `error.HasHostBits` to handle.pub fn init(address: Ipv6Address, prefix_len: u8) InitError!Ipv6Interface { if (prefix_len > Ipv6Address.bit_count) return error.InvalidPrefixLength; return .{ .address = address, .prefix_len = prefix_len };}
/// The `/128` interface holding `address` alone, which is what text carrying/// no `/` parses to.pub fn fromAddress(address: Ipv6Address) Ipv6Interface { return .{ .address = address, .prefix_len = Ipv6Address.bit_count };}
pub const ParseError = Ipv6Address.ParseError || Ipv6Network.PrefixError;
/// Parses `address/prefix`, as in `2001:db8::1/64`.////// Both halves are read as strictly as they are on their own. Text with no `/`/// at all is read as a `/128`.////// Host bits are kept rather than rejected or cleared, which is the whole of/// the difference from `Ipv6Network.parse` and `Ipv6Network.parseTruncate`.pub fn parse(text: []const u8) ParseError!Ipv6Interface { const slash = std.mem.findScalar(u8, text, '/') orelse return .{ .address = try Ipv6Address.parse(text), .prefix_len = Ipv6Address.bit_count, }; return .{ .address = try Ipv6Address.parse(text[0..slash]), .prefix_len = try Ipv6Network.parsePrefixLen(text[slash + 1 ..]), };}
/// Whether `text` is a valid `address/prefix`, discarding the reason when it/// is not.pub fn isValid(text: []const u8) bool { _ = parse(text) catch return false; return true;}
/// The network the interface sits on, with the host bits cleared: the/// `2001:db8::/64` of a `2001:db8::1/64`.pub fn network(i: Ipv6Interface) Ipv6Network { // The prefix length is in range by construction, so the only error // `initTruncate` reports cannot happen here. return Ipv6Network.initTruncate(i.address, i.prefix_len) catch unreachable;}
/// The netmask, as in `ffff:ffff:ffff:ffff::` for a `/64`.pub fn netmask(i: Ipv6Interface) Ipv6Address { return i.network().netmask();}
/// The complement of the netmask, as in `::ffff:ffff:ffff:ffff` for a `/64`.pub fn hostmask(i: Ipv6Interface) Ipv6Address { return i.network().hostmask();}
/// The network address of the network the interface sits on.pub fn networkAddress(i: Ipv6Interface) Ipv6Address { return i.network().address;}
/// The last address of the network the interface sits on.pub fn lastAddress(i: Ipv6Interface) Ipv6Address { return i.network().lastAddress();}
/// The host bits on their own, as in `::1` for `2001:db8::1/64`. This is the/// part of the address the network does not determine, and for a `/64` it is/// the interface identifier.pub fn hostBits(i: Ipv6Interface) Ipv6Address { return .fromInt(i.address.toInt() & i.hostmask().toInt());}
/// Whether the address is the network address of its own network, which a link/// reserves as its subnet-router anycast address (RFC 4291). False for a/// `/127`, which is a point-to-point link using both of its addresses/// (RFC 6164), and for a `/128`, which is a single host.pub fn isNetworkAddress(i: Ipv6Interface) bool { return i.prefix_len < 127 and i.address.eql(i.networkAddress());}
/// Whether the address is one a host may be given: anything but the/// subnet-router anycast address of a `/126` or shorter prefix. IPv6 has no/// broadcast address, so the top of a network is usable.pub fn isHostAddress(i: Ipv6Interface) bool { return !i.isNetworkAddress();}
pub fn eql(i: Ipv6Interface, other: Ipv6Interface) bool { return i.prefix_len == other.prefix_len and i.address.eql(other.address);}
/// Orders by address first, then by prefix length, so that two interfaces at/// the same address sort with the wider network first.pub fn order(i: Ipv6Interface, other: Ipv6Interface) std.math.Order { return switch (i.address.order(other.address)) { .eq => std.math.order(i.prefix_len, other.prefix_len), else => |result| result, };}
/// The longest text an IPv6 interface can format to.pub const max_text_len = Ipv6Address.max_text_len + "/128".len;
/// Writes `address/prefix`. Use the `{f}` specifier.pub fn format(i: Ipv6Interface, w: *Writer) Writer.Error!void { var buffer: [render_len]u8 = undefined; try w.writeAll(i.render(&buffer));}
/// Formats into `buffer`, returning the written slice. The buffer must be at/// least `max_text_len` bytes.pub fn bufPrint(i: Ipv6Interface, buffer: []u8) error{NoSpaceLeft}![]u8 { var rendered: [render_len]u8 = undefined; const text = i.render(&rendered); if (buffer.len < text.len) return error.NoSpaceLeft; @memcpy(buffer[0..text.len], text); return buffer[0..text.len];}
/// Room for the longest text plus the spill of `decimal.renderSmall`.const render_len = Ipv6Address.max_text_len + "/".len + 4;
/// Renders `address/prefix` into `buffer`, returning the written slice. This/// is the one place the text is produced; `format` and `bufPrint` both go/// through it rather than through `Writer.print`, whose per-integer formatting/// costs more than the whole interface.fn render(i: Ipv6Interface, buffer: *[render_len]u8) []u8 { const address = i.address.bufPrint(buffer[0..Ipv6Address.max_text_len]) catch unreachable; var len = address.len; buffer[len] = '/'; len += 1; len += decimal.renderSmall(i.prefix_len, buffer[len..][0..4]); return buffer[0..len];}
/// Writes the value as a JSON string. See `json.stringify`.pub fn jsonStringify(value: Ipv6Interface, 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,) !Ipv6Interface { _ = options; return json.parse(Ipv6Interface, allocator, source);}
const testing = std.testing;
test parse { const i = try parse("2001:db8::1/64"); try testing.expectEqual(try Ipv6Address.parse("2001:db8::1"), i.address); try testing.expectEqual(@as(u8, 64), i.prefix_len);
// The host bits a network would reject or clear are kept as they are. try testing.expect((try parse("2001:db8::1/32")).eql(try init(try .parse("2001:db8::1"), 32))); try testing.expect((try parse("fe80::1/10")).eql(try init(try .parse("fe80::1"), 10))); try testing.expect((try parse("2001:db8::1/0")).eql(try init(try .parse("2001:db8::1"), 0))); try testing.expect((try parse("::1/128")).eql(loopback));
// Text without a prefix is a single host. try testing.expect((try parse("::1")).eql(fromAddress(.loopback)));}
test "parse rejects malformed text" { // Everything the network parser rejects but the host bits. try testing.expectError(error.InvalidPrefixLength, parse("2001:db8::1/129")); try testing.expectError(error.InvalidPrefix, parse("2001:db8::1/")); try testing.expectError(error.InvalidPrefix, parse("2001:db8::1/064")); try testing.expectError(error.InvalidPrefix, parse("2001:db8::1/1000")); try testing.expectError(error.InvalidPrefix, parse("2001:db8::1/x")); try testing.expectError(error.InvalidPrefix, parse("2001:db8::1/64 ")); try testing.expectError(error.TooFewGroups, parse("2001:db8/64")); // A zone identifier belongs to `Ipv6Address.parseZoned`, not here. try testing.expectError(error.UnexpectedZone, parse("fe80::1%eth0/64"));
try testing.expect(isValid("2001:db8::1/64")); // The one thing an interface accepts that a network does not. try testing.expect(isValid("2001:db8::1/64") and !Ipv6Network.isValid("2001:db8::1/64")); try testing.expect(!isValid("2001:db8::1/129"));
try testing.expectError(error.InvalidPrefixLength, init(.loopback, 129));}
test network { const i = try parse("2001:db8::1/64"); try testing.expect(i.network().eql(try Ipv6Network.parse("2001:db8::/64"))); try testing.expectFmt("2001:db8::", "{f}", .{i.networkAddress()}); try testing.expectFmt("2001:db8::ffff:ffff:ffff:ffff", "{f}", .{i.lastAddress()}); try testing.expectFmt("ffff:ffff:ffff:ffff::", "{f}", .{i.netmask()}); try testing.expectFmt("::ffff:ffff:ffff:ffff", "{f}", .{i.hostmask()}); // For a /64 the host bits are the interface identifier. try testing.expectFmt("::1", "{f}", .{i.hostBits()});
// A /128 is its own network, and a /0 keeps the whole address as host bits. try testing.expect(loopback.network().eql(Ipv6Network.fromHost(.loopback))); try testing.expectFmt("::", "{f}", .{loopback.hostBits()}); try testing.expectFmt("2001:db8::1", "{f}", .{(try parse("2001:db8::1/0")).hostBits()});
// The network an interface reports is the one that contains it. try testing.expect(i.network().contains(i.address)); try testing.expect(loopback.network().contains(loopback.address));}
test "host and network addresses" { try testing.expect((try parse("2001:db8::/64")).isNetworkAddress()); try testing.expect(!(try parse("2001:db8::/64")).isHostAddress()); try testing.expect((try parse("2001:db8::1/64")).isHostAddress()); try testing.expect(!(try parse("2001:db8::1/64")).isNetworkAddress()); // Unlike IPv4, the top of a network is an ordinary host address. try testing.expect((try parse("2001:db8::ffff:ffff:ffff:ffff/64")).isHostAddress());
// A point-to-point link and a single host reserve neither of their // addresses (RFC 6164). for ([_][]const u8{ "2001:db8::/127", "2001:db8::1/127", "2001:db8::/128" }) |text| { const i = try parse(text); try testing.expect(i.isHostAddress()); try testing.expect(!i.isNetworkAddress()); }}
test jsonStringify { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try std.json.Stringify.value(try Ipv6Interface.parse("2001:db8::1/64"), .{}, &w); // A JSON string holding exactly what `format` would have written. try testing.expectEqualStrings("\"2001:db8::1/64\"", w.buffered());}
test jsonParse { // The hook is driven directly rather than through `parseFromSlice`, so // that this tests the function it is named after and nothing else; // `root.zig` has the end-to-end one. var scanner = std.json.Scanner.initCompleteInput(testing.allocator, "\"2001:db8::1/64\""); defer scanner.deinit(); const value = try Ipv6Interface.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Ipv6Interface.parse("2001:db8::1/64")));
// 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/129\""); defer bad.deinit(); try testing.expectError( error.InvalidCharacter, Ipv6Interface.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, Ipv6Interface.jsonParse(testing.allocator, &number, .{}), );}
test format { try testing.expectFmt("2001:db8::1/64", "{f}", .{try parse("2001:db8::1/64")}); try testing.expectFmt("::1/128", "{f}", .{loopback}); try testing.expectFmt("fe80::1/10", "{f}", .{try parse("fe80::1/10")}); try testing.expectFmt("::/0", "{f}", .{try parse("::/0")});
var buffer: [max_text_len]u8 = undefined; const full = try parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128"); try testing.expectEqualStrings( "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128", try full.bufPrint(&buffer), ); try testing.expectError(error.NoSpaceLeft, full.bufPrint(buffer[0..4]));}
test "round trip through text" { const cases = [_][]const u8{ "::/0", "::1/128", "fe80::1/10", "2001:db8::1/64", "::ffff:192.0.2.1/96", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128", }; for (cases) |text| { var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings(text, try (try parse(text)).bufPrint(&buffer)); }}
test "equality and ordering" { try testing.expect((try parse("2001:db8::1/64")).eql(try init(try .parse("2001:db8::1"), 64))); // The prefix length is part of the value, unlike the network it implies. try testing.expect(!(try parse("2001:db8::1/64")).eql(try parse("2001:db8::1/48")));
try testing.expectEqual(.lt, (try parse("2001:db8::1/48")).order(try parse("2001:db8::1/64"))); try testing.expectEqual(.lt, (try parse("2001:db8::1/64")).order(try parse("2001:db8::2/48"))); try testing.expectEqual(.eq, (try parse("2001:db8::1/64")).order(try parse("2001:db8::1/64")));}
test "parsing works at comptime" { const i = comptime parse("2001:db8::1/64") catch unreachable; comptime std.debug.assert(i.prefix_len == 64); comptime std.debug.assert(i.network().eql(Ipv6Network.parse("2001:db8::/64") catch unreachable));}
test init { const eth0 = try Ipv6Interface.init(try .parse("2001:db8::1"), 64); try testing.expect(eth0.eql(try parse("2001:db8::1/64"))); // Host bits are the point of an interface, so there is no rejecting them. try testing.expectError(error.InvalidPrefixLength, Ipv6Interface.init(.loopback, 129));}
test fromAddress { const host = Ipv6Interface.fromAddress(try .parse("2001:db8::1")); try testing.expectEqual(@as(u8, 128), host.prefix_len); try testing.expect(host.eql(try parse("2001:db8::1")));}
test isValid { try testing.expect(isValid("2001:db8::1/64")); // Host bits are kept rather than rejected, which is the difference from a // network. try testing.expect(isValid("2001:db8::/64")); try testing.expect(!isValid("2001:db8::1/129"));}
test netmask { try testing.expect((try parse("2001:db8::1/64")) .netmask().eql(try .parse("ffff:ffff:ffff:ffff::")));}
test hostmask { try testing.expect((try parse("2001:db8::1/64")) .hostmask().eql(try .parse("::ffff:ffff:ffff:ffff")));}
test networkAddress { try testing.expect((try parse("2001:db8::1/64")) .networkAddress().eql(try .parse("2001:db8::")));}
test lastAddress { try testing.expect((try parse("2001:db8::1/64")) .lastAddress().eql(try .parse("2001:db8::ffff:ffff:ffff:ffff")));}
test hostBits { // The part of the address the network does not determine, which for a // `/64` is the interface identifier. try testing.expect((try parse("2001:db8::1/64")).hostBits().eql(try .parse("::1"))); try testing.expect((try parse("2001:db8:1::1/32")).hostBits().eql(try .parse("0:0:1::1")));}
test isNetworkAddress { // A link reserves this one as its subnet-router anycast address. try testing.expect((try parse("2001:db8::/64")).isNetworkAddress()); try testing.expect(!(try parse("2001:db8::1/64")).isNetworkAddress()); // A `/127` is a point-to-point link using both of its addresses. try testing.expect(!(try parse("2001:db8::/127")).isNetworkAddress());}
test isHostAddress { try testing.expect((try parse("2001:db8::1/64")).isHostAddress()); try testing.expect(!(try parse("2001:db8::/64")).isHostAddress()); // IPv6 has no broadcast address, so the top of a network is usable. try testing.expect((try parse("2001:db8::ffff:ffff:ffff:ffff/64")).isHostAddress());}
test eql { try testing.expect((try parse("2001:db8::1/64")).eql(try parse("2001:0db8::1/64"))); // The prefix length is part of the interface, not just the address. try testing.expect(!(try parse("2001:db8::1/64")).eql(try parse("2001:db8::1/48")));}
test order { // Two interfaces at the same address sort with the wider network first. try testing.expectEqual(.lt, (try parse("2001:db8::1/48")).order(try parse("2001:db8::1/64"))); try testing.expectEqual(.lt, (try parse("::1/128")).order(try parse("2001:db8::1/64"))); try testing.expectEqual(.eq, (try parse("::1/128")).order(try parse("::1/128")));}
test bufPrint { var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings( "2001:db8::1/64", try (try parse("2001:db8::1/64")).bufPrint(&buffer), );
var small: [4]u8 = undefined; try testing.expectError(error.NoSpaceLeft, (try parse("2001:db8::1/64")).bufPrint(&small));}
test render { // The one place the text is produced; `format` and `bufPrint` both go // through it. var buffer: [render_len]u8 = undefined; try testing.expectEqualStrings("2001:db8::1/64", (try parse("2001:db8::1/64")).render(&buffer)); try testing.expectEqualStrings("::/0", (try parse("::/0")).render(&buffer)); try testing.expectEqualStrings("::1/128", (try parse("::1")).render(&buffer));}