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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An IPv4 address together with the prefix length of the network it sits on,//! as in `192.168.1.42/24`: what is configured on an interface, and what//! `ip addr` prints.//!//! This is the counterpart of `Ipv4Network`, 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 Ipv4Interface.parse("192.168.1.42/24");//! // 192.168.1.42 on 192.168.1.0/24, netmask 255.255.255.0//! ```
const std = @import("std");const json = @import("json.zig");const Writer = std.Io.Writer;
const decimal = @import("decimal.zig");const Ipv4Address = @import("Ipv4Address.zig");const Ipv4Network = @import("Ipv4Network.zig");
const Ipv4Interface = @This();
/// The address, with whatever host bits it was given.address: Ipv4Address,/// Length of the routing prefix in bits, at most 32. `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, `127.0.0.1/8`.pub const loopback: Ipv4Interface = .{ .address = .loopback, .prefix_len = 8 };
pub const InitError = error{ /// The prefix length was greater than 32. InvalidPrefixLength,};
/// Builds an interface. Unlike `Ipv4Network.init`, the host bits of `address`/// may be anything, so there is no `error.HasHostBits` to handle.pub fn init(address: Ipv4Address, prefix_len: u8) InitError!Ipv4Interface { if (prefix_len > Ipv4Address.bit_count) return error.InvalidPrefixLength; return .{ .address = address, .prefix_len = prefix_len };}
/// The `/32` interface holding `address` alone, which is what text carrying no/// `/` parses to.pub fn fromAddress(address: Ipv4Address) Ipv4Interface { return .{ .address = address, .prefix_len = Ipv4Address.bit_count };}
pub const ParseError = Ipv4Address.ParseError || Ipv4Network.PrefixError;
/// Parses `address/prefix`, as in `192.168.1.42/24`.////// Both halves are read as strictly as they are on their own, and a/// dotted-decimal netmask is accepted in place of a prefix length, as in/// `192.168.1.42/255.255.255.0`. Text with no `/` at all is read as a `/32`.////// Host bits are kept rather than rejected or cleared, which is the whole of/// the difference from `Ipv4Network.parse` and `Ipv4Network.parseTruncate`.pub fn parse(text: []const u8) ParseError!Ipv4Interface { // A plain loop, because on text this short the vectorized // `std.mem.findScalar` costs more in setup than it saves. const slash: ?usize = for (text, 0..) |c, i| { if (c == '/') break i; } else null; return .{ .address = try Ipv4Address.parse(text[0 .. slash orelse text.len]), .prefix_len = if (slash) |index| try Ipv4Network.parsePrefixLen(text[index + 1 ..]) else Ipv4Address.bit_count, };}
/// 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/// `192.168.1.0/24` of a `192.168.1.42/24`.pub fn network(i: Ipv4Interface) Ipv4Network { // The prefix length is in range by construction, so the only error // `initTruncate` reports cannot happen here. return Ipv4Network.initTruncate(i.address, i.prefix_len) catch unreachable;}
/// The netmask, as in `255.255.255.0` for a `/24`.pub fn netmask(i: Ipv4Interface) Ipv4Address { return i.network().netmask();}
/// The complement of the netmask, as in `0.0.0.255` for a `/24`.pub fn hostmask(i: Ipv4Interface) Ipv4Address { return i.network().hostmask();}
/// The network address of the network the interface sits on.pub fn networkAddress(i: Ipv4Interface) Ipv4Address { return i.network().address;}
/// The directed broadcast address of the network the interface sits on.pub fn broadcastAddress(i: Ipv4Interface) Ipv4Address { return i.network().broadcastAddress();}
/// The host bits on their own, as in `0.0.0.42` for `192.168.1.42/24`. This is/// the part of the address the network does not determine.pub fn hostBits(i: Ipv4Interface) Ipv4Address { return .fromInt(i.address.toInt() & i.hostmask().toInt());}
/// Whether the address is the network address of its own network, as/// `192.168.1.0/24` is. False for a `/31` or `/32`, which reserve neither of/// their addresses (RFC 3021).pub fn isNetworkAddress(i: Ipv4Interface) bool { return i.prefix_len < 31 and i.address.eql(i.networkAddress());}
/// Whether the address is the directed broadcast address of its own network,/// as `192.168.1.255/24` is. False for a `/31` or `/32`, as above.pub fn isBroadcastAddress(i: Ipv4Interface) bool { return i.prefix_len < 31 and i.address.eql(i.broadcastAddress());}
/// Whether the address is one a host may be given: anything but the network/// and broadcast addresses of a `/30` or shorter prefix.pub fn isHostAddress(i: Ipv4Interface) bool { return !i.isNetworkAddress() and !i.isBroadcastAddress();}
pub fn eql(i: Ipv4Interface, other: Ipv4Interface) 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: Ipv4Interface, other: Ipv4Interface) 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 IPv4 interface can format to, as in/// `255.255.255.255/32`.pub const max_text_len = Ipv4Address.max_text_len + "/32".len;
/// Writes `address/prefix`. Use the `{f}` specifier.pub fn format(i: Ipv4Interface, 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: Ipv4Interface, 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 byte of slack the address's `bufPrint`/// wants to render in place and the spill of `decimal.renderSmall`.const render_len = Ipv4Address.max_text_len + 1 + "/".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: Ipv4Interface, buffer: *[render_len]u8) []u8 { const address = i.address.bufPrint(buffer[0 .. Ipv4Address.max_text_len + 1]) 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: Ipv4Interface, 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,) !Ipv4Interface { _ = options; return json.parse(Ipv4Interface, allocator, source);}
const testing = std.testing;
test parse { const i = try parse("192.168.1.42/24"); try testing.expectEqual(Ipv4Address.init(192, 168, 1, 42), i.address); try testing.expectEqual(@as(u8, 24), i.prefix_len);
// The host bits a network would reject or clear are kept as they are. try testing.expect((try parse("192.168.1.42/255.255.255.0")).eql(i)); try testing.expect((try parse("10.1.2.3/8")).eql(try init(.init(10, 1, 2, 3), 8))); try testing.expect((try parse("10.1.2.3/0")).eql(try init(.init(10, 1, 2, 3), 0))); try testing.expect((try parse("127.0.0.1/8")).eql(loopback));
// Text without a prefix is a single host. try testing.expect((try parse("192.0.2.1")).eql(fromAddress(.init(192, 0, 2, 1)))); try testing.expect((try parse("192.0.2.1/32")).eql(fromAddress(.init(192, 0, 2, 1))));}
test "parse rejects malformed text" { // Everything the network parser rejects but the host bits. try testing.expectError(error.InvalidPrefixLength, parse("192.168.1.42/33")); try testing.expectError(error.InvalidPrefix, parse("192.168.1.42/")); try testing.expectError(error.InvalidPrefix, parse("192.168.1.42/24 ")); try testing.expectError(error.InvalidPrefix, parse("192.168.1.42/024")); try testing.expectError(error.InvalidPrefix, parse("192.168.1.42/x")); try testing.expectError(error.NonContiguousNetmask, parse("10.0.0.1/255.0.255.0")); try testing.expectError(error.TooFewOctets, parse("192.168.1/24")); try testing.expectError(error.OctetOutOfRange, parse("192.168.1.256/24")); try testing.expectError(error.LeadingZero, parse("192.168.01.42/24"));
try testing.expect(isValid("192.168.1.42/24")); // The one thing an interface accepts that a network does not. try testing.expect(isValid("192.168.1.42/24") and !Ipv4Network.isValid("192.168.1.42/24")); try testing.expect(!isValid("192.168.1.42/33"));
try testing.expectError(error.InvalidPrefixLength, init(.loopback, 33));}
test network { const i = try parse("192.168.1.42/24"); try testing.expect(i.network().eql(try Ipv4Network.parse("192.168.1.0/24"))); try testing.expectFmt("192.168.1.0", "{f}", .{i.networkAddress()}); try testing.expectFmt("192.168.1.255", "{f}", .{i.broadcastAddress()}); try testing.expectFmt("255.255.255.0", "{f}", .{i.netmask()}); try testing.expectFmt("0.0.0.255", "{f}", .{i.hostmask()}); try testing.expectFmt("0.0.0.42", "{f}", .{i.hostBits()});
// A /32 is its own network, and a /0 keeps the whole address as host bits. try testing.expect((fromAddress(.loopback)).network().eql(Ipv4Network.fromHost(.loopback))); try testing.expectFmt("127.0.0.1", "{f}", .{(try parse("127.0.0.1/0")).hostBits()}); try testing.expectFmt("0.0.0.0", "{f}", .{(fromAddress(.loopback)).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, network and broadcast addresses" { try testing.expect((try parse("192.168.1.0/24")).isNetworkAddress()); try testing.expect(!(try parse("192.168.1.0/24")).isHostAddress()); try testing.expect((try parse("192.168.1.255/24")).isBroadcastAddress()); try testing.expect(!(try parse("192.168.1.255/24")).isHostAddress()); try testing.expect((try parse("192.168.1.42/24")).isHostAddress()); try testing.expect(!(try parse("192.168.1.42/24")).isNetworkAddress()); try testing.expect(!(try parse("192.168.1.42/24")).isBroadcastAddress());
// A point-to-point link and a single host reserve neither of their // addresses, so both ends of a /31 are usable (RFC 3021). for ([_][]const u8{ "192.0.2.0/31", "192.0.2.1/31", "192.0.2.0/32", "192.0.2.1/32" }) |text| { const i = try parse(text); try testing.expect(i.isHostAddress()); try testing.expect(!i.isNetworkAddress()); try testing.expect(!i.isBroadcastAddress()); }}
test jsonStringify { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try std.json.Stringify.value(try Ipv4Interface.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`, 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, "\"192.0.2.1/24\""); defer scanner.deinit(); const value = try Ipv4Interface.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Ipv4Interface.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, Ipv4Interface.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, Ipv4Interface.jsonParse(testing.allocator, &number, .{}), );}
test format { try testing.expectFmt("192.168.1.42/24", "{f}", .{try parse("192.168.1.42/24")}); try testing.expectFmt("127.0.0.1/8", "{f}", .{loopback}); try testing.expectFmt("192.0.2.1/32", "{f}", .{fromAddress(.init(192, 0, 2, 1))}); try testing.expectFmt("0.0.0.0/0", "{f}", .{try parse("0.0.0.0/0")});
var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings("255.255.255.255/32", try (fromAddress(.broadcast)).bufPrint(&buffer)); try testing.expectError(error.NoSpaceLeft, (fromAddress(.broadcast)).bufPrint(buffer[0..4]));}
test "round trip through text" { const cases = [_][]const u8{ "0.0.0.0/0", "10.1.2.3/8", "127.0.0.1/8", "192.168.1.42/24", "255.255.255.255/32", }; 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("192.168.1.42/24")).eql(try init(.init(192, 168, 1, 42), 24))); // The prefix length is part of the value, unlike the network it implies. try testing.expect(!(try parse("192.168.1.42/24")).eql(try parse("192.168.1.42/25")));
try testing.expectEqual(.lt, (try parse("192.168.1.42/24")).order(try parse("192.168.1.42/25"))); try testing.expectEqual(.lt, (try parse("192.168.1.42/24")).order(try parse("192.168.1.43/8"))); try testing.expectEqual(.eq, (try parse("192.168.1.42/24")).order(try parse("192.168.1.42/24")));}
test "parsing works at comptime" { const i = comptime parse("192.168.1.42/24") catch unreachable; comptime std.debug.assert(i.prefix_len == 24); comptime std.debug.assert(i.network().eql(Ipv4Network.parse("192.168.1.0/24") catch unreachable));}
test init { const eth0 = try Ipv4Interface.init(try .parse("192.168.1.42"), 24); try testing.expect(eth0.eql(try parse("192.168.1.42/24"))); // Host bits are the point of an interface, so there is no rejecting them. try testing.expectError(error.InvalidPrefixLength, Ipv4Interface.init(.loopback, 33));}
test fromAddress { const host = Ipv4Interface.fromAddress(try .parse("192.0.2.1")); try testing.expectEqual(@as(u8, 32), host.prefix_len); try testing.expect(host.eql(try parse("192.0.2.1")));}
test isValid { try testing.expect(isValid("192.168.1.42/24")); // Host bits are kept rather than rejected, which is the difference from a // network. try testing.expect(isValid("192.168.1.0/24")); try testing.expect(!isValid("192.168.1.42/33"));}
test netmask { try testing.expect((try parse("192.168.1.42/24")).netmask().eql(try .parse("255.255.255.0")));}
test hostmask { try testing.expect((try parse("192.168.1.42/24")).hostmask().eql(try .parse("0.0.0.255")));}
test networkAddress { try testing.expect((try parse("192.168.1.42/24")) .networkAddress().eql(try .parse("192.168.1.0")));}
test broadcastAddress { try testing.expect((try parse("192.168.1.42/24")) .broadcastAddress().eql(try .parse("192.168.1.255")));}
test hostBits { // The part of the address the network does not determine. try testing.expect((try parse("192.168.1.42/24")).hostBits().eql(try .parse("0.0.0.42"))); try testing.expect((try parse("192.168.1.42/16")).hostBits().eql(try .parse("0.0.1.42")));}
test isNetworkAddress { try testing.expect((try parse("192.168.1.0/24")).isNetworkAddress()); try testing.expect(!(try parse("192.168.1.42/24")).isNetworkAddress()); // A `/31` reserves neither of its addresses (RFC 3021). try testing.expect(!(try parse("192.0.2.0/31")).isNetworkAddress());}
test isBroadcastAddress { try testing.expect((try parse("192.168.1.255/24")).isBroadcastAddress()); try testing.expect(!(try parse("192.168.1.42/24")).isBroadcastAddress()); try testing.expect(!(try parse("192.0.2.1/31")).isBroadcastAddress());}
test isHostAddress { try testing.expect((try parse("192.168.1.42/24")).isHostAddress()); try testing.expect(!(try parse("192.168.1.0/24")).isHostAddress()); try testing.expect(!(try parse("192.168.1.255/24")).isHostAddress()); // Both addresses of a point-to-point link are usable. try testing.expect((try parse("192.0.2.0/31")).isHostAddress());}
test eql { try testing.expect((try parse("192.168.1.42/24")).eql(try parse("192.168.1.42/24"))); // The prefix length is part of the interface, not just the address. try testing.expect(!(try parse("192.168.1.42/24")).eql(try parse("192.168.1.42/16")));}
test order { // Two interfaces at the same address sort with the wider network first. try testing.expectEqual(.lt, (try parse("192.168.1.42/16")).order(try parse("192.168.1.42/24"))); try testing.expectEqual(.lt, (try parse("10.0.0.1/8")).order(try parse("192.168.1.42/24"))); try testing.expectEqual(.eq, (try parse("10.0.0.1/8")).order(try parse("10.0.0.1/8")));}
test bufPrint { var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings( "192.168.1.42/24", try (try parse("192.168.1.42/24")).bufPrint(&buffer), );
var small: [4]u8 = undefined; try testing.expectError(error.NoSpaceLeft, (try parse("192.168.1.42/24")).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("192.168.1.42/24", (try parse("192.168.1.42/24")).render(&buffer)); try testing.expectEqualStrings("0.0.0.0/0", (try parse("0.0.0.0/0")).render(&buffer)); try testing.expectEqualStrings("255.255.255.255/32", (try parse("255.255.255.255")).render(&buffer));}