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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An inclusive range of IP addresses 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 Network = @import("network.zig").Network;const Ipv4Range = @import("Ipv4Range.zig");const Ipv6Range = @import("Ipv6Range.zig");
/// An inclusive range of addresses of one version, for code that handles both/// without caring which it has.////// See `Ipv4Range` for what a range is for and why CIDR notation cannot say/// it. A range never spans the two versions: the address space of one has/// nothing to do with the address space of the other, so the two ends of a/// range are always of the same family.pub const Range = union(Family) { ipv4: Ipv4Range, ipv6: Ipv6Range,
pub const InitError = Ipv4Range.InitError || error{ /// The two ends were of different versions, which is not a range of /// anything. MixedFamilies, };
/// Builds a range from its two ends, both of which are part of it and /// both of which must be of the same version. The parameters are named /// `low` and `high` rather than after the `first` and `last` accessors /// below, which they would otherwise shadow. pub fn init(low: Address, high: Address) InitError!Range { return switch (low) { .ipv4 => |lo| switch (high) { .ipv4 => |hi| .{ .ipv4 = try .init(lo, hi) }, .ipv6 => error.MixedFamilies, }, .ipv6 => |lo| switch (high) { .ipv4 => error.MixedFamilies, .ipv6 => |hi| .{ .ipv6 = try .init(lo, hi) }, }, }; }
/// The range a network covers, from its network address to its last /// address. pub fn fromNetwork(n: Network) Range { return switch (n) { .ipv4 => |v4| .{ .ipv4 = .fromNetwork(v4) }, .ipv6 => |v6| .{ .ipv6 = .fromNetwork(v6) }, }; }
/// The range holding one address. pub fn fromAddress(address: Address) Range { return switch (address) { .ipv4 => |v4| .{ .ipv4 = .fromAddress(v4) }, .ipv6 => |v6| .{ .ipv6 = .fromAddress(v6) }, }; }
pub const ParseError = Ipv4Range.ParseError || Ipv6Range.ParseError;
/// Parses `first-last` of either version. Text holding a `:` is read as /// IPv6 and everything else as IPv4, so the error returned is always the /// one from the version the text was reaching for. pub fn parse(text: []const u8) ParseError!Range { if (std.mem.findScalar(u8, text, ':') != null) { return .{ .ipv6 = try .parse(text) }; } return .{ .ipv4 = try .parse(text) }; }
/// Whether `text` is a valid range of either version, discarding the /// reason when it is not. pub fn isValid(text: []const u8) bool { _ = parse(text) catch return false; return true; }
/// Which version the range belongs to. pub fn family(r: Range) Family { return r; }
/// The lowest address in the range. pub fn first(r: Range) Address { return switch (r) { .ipv4 => |v4| .{ .ipv4 = v4.first }, .ipv6 => |v6| .{ .ipv6 = v6.first }, }; }
/// The highest address in the range, which is part of it. pub fn last(r: Range) Address { return switch (r) { .ipv4 => |v4| .{ .ipv4 = v4.last }, .ipv6 => |v6| .{ .ipv6 = v6.last }, }; }
/// The number of addresses in the range, which is never zero. The result /// is 129 bits wide because an IPv6 range can cover 2^128 addresses. pub fn addressCount(r: Range) u129 { return switch (r) { inline else => |range| range.addressCount(), }; }
/// Whether the range holds exactly one address. pub fn isSingleAddress(r: Range) bool { return switch (r) { inline else => |range| range.isSingleAddress(), }; }
/// Whether `address` falls inside the range. An address of the other /// version never does. pub fn contains(r: Range, address: Address) bool { return switch (r) { .ipv4 => |v4| address == .ipv4 and v4.contains(address.ipv4), .ipv6 => |v6| address == .ipv6 and v6.contains(address.ipv6), }; }
/// Whether every address of `other` is also in this range. A range of the /// other version is never contained. pub fn containsRange(r: Range, other: Range) bool { return switch (r) { .ipv4 => |v4| other == .ipv4 and v4.containsRange(other.ipv4), .ipv6 => |v6| other == .ipv6 and v6.containsRange(other.ipv6), }; }
/// Whether the two ranges have any address in common. Ranges of different /// versions never do. pub fn overlaps(r: Range, other: Range) bool { return switch (r) { .ipv4 => |v4| other == .ipv4 and v4.overlaps(other.ipv4), .ipv6 => |v6| other == .ipv6 and v6.overlaps(other.ipv6), }; }
/// The range as a single network, or null when it is not one. pub fn toNetwork(r: Range) ?Network { return switch (r) { .ipv4 => |v4| if (v4.toNetwork()) |n| .{ .ipv4 = n } else null, .ipv6 => |v6| if (v6.toNetwork()) |n| .{ .ipv6 = n } else null, }; }
/// The smallest set of whole networks that covers the range exactly. See /// `Ipv4Range.prefixes`. pub fn prefixes(r: Range) PrefixIterator { return switch (r) { .ipv4 => |v4| .{ .ipv4 = v4.prefixes() }, .ipv6 => |v6| .{ .ipv6 = v6.prefixes() }, }; }
pub const PrefixIterator = union(Family) { ipv4: Ipv4Range.PrefixIterator, ipv6: Ipv6Range.PrefixIterator,
pub fn next(it: *PrefixIterator) ?Network { return switch (it.*) { .ipv4 => |*v4| if (v4.next()) |n| .{ .ipv4 = n } else null, .ipv6 => |*v6| if (v6.next()) |n| .{ .ipv6 = n } else null, }; }
test next { var it = (try Range.parse("10.0.0.10-10.0.0.20")).prefixes(); try testing.expect(it.next().?.eql(try .parse("10.0.0.10/31"))); try testing.expect(it.next().?.eql(try .parse("10.0.0.12/30"))); try testing.expect(it.next().?.eql(try .parse("10.0.0.16/30"))); try testing.expect(it.next().?.eql(try .parse("10.0.0.20/32"))); try testing.expectEqual(null, it.next()); } };
/// Iterates over every address in the range. pub fn addresses(r: Range) AddressIterator { return switch (r) { .ipv4 => |v4| .{ .ipv4 = v4.addresses() }, .ipv6 => |v6| .{ .ipv6 = v6.addresses() }, }; }
pub const AddressIterator = union(Family) { ipv4: Ipv4Range.AddressIterator, ipv6: Ipv6Range.AddressIterator,
pub fn next(it: *AddressIterator) ?Address { return switch (it.*) { .ipv4 => |*v4| if (v4.next()) |a| .{ .ipv4 = a } else null, .ipv6 => |*v6| if (v6.next()) |a| .{ .ipv6 = a } else null, }; }
test next { var it = (try Range.parse("2001:db8::1-2001:db8::3")).addresses(); try testing.expect(it.next().?.eql(try .parse("2001:db8::1"))); try testing.expect(it.next().?.eql(try .parse("2001:db8::2"))); try testing.expect(it.next().?.eql(try .parse("2001:db8::3"))); try testing.expectEqual(null, it.next()); } };
/// Sorts `ranges` in place and folds it down to the smallest set covering /// exactly the same addresses. See `Ipv4Range.merge`. /// /// A mixed slice is fine. Sorting puts every IPv4 range ahead of every /// IPv6 one and nothing joins across the boundary, so the two versions /// are merged independently and come back in that order. pub fn merge(ranges: []Range) []Range { std.mem.sortUnstable(Range, ranges, {}, lessThan); var kept: usize = 0; for (ranges) |candidate| { if (kept > 0) { if (join(ranges[kept - 1], candidate)) |joined| { ranges[kept - 1] = joined; continue; } } ranges[kept] = candidate; kept += 1; } return ranges[0..kept]; }
fn lessThan(_: void, a: Range, b: Range) bool { return a.order(b) == .lt; }
/// The one range covering both exactly, when they overlap or touch, and /// null when a gap separates them or they are of different versions. See /// `Ipv4Range.join`. pub fn join(a: Range, b: Range) ?Range { return switch (a) { .ipv4 => |v4| if (b == .ipv4) if (v4.join(b.ipv4)) |range| .{ .ipv4 = range } else null else null, .ipv6 => |v6| if (b == .ipv6) if (v6.join(b.ipv6)) |range| .{ .ipv6 = range } else null else null, }; }
pub fn eql(r: Range, other: Range) bool { return switch (r) { .ipv4 => |v4| other == .ipv4 and v4.eql(other.ipv4), .ipv6 => |v6| other == .ipv6 and v6.eql(other.ipv6), }; }
/// Orders IPv4 ranges before IPv6 ones, and within a version by the low /// end first and then the high end, matching `Address.order`. pub fn order(r: Range, other: Range) std.math.Order { return switch (r) { .ipv4 => |v4| switch (other) { .ipv4 => |o| v4.order(o), .ipv6 => .lt, }, .ipv6 => |v6| switch (other) { .ipv4 => .gt, .ipv6 => |o| v6.order(o), }, }; }
/// The longest text a range of either version can format to. pub const max_text_len = @max(Ipv4Range.max_text_len, Ipv6Range.max_text_len);
/// Writes the range as `first-last`. Use the `{f}` specifier. pub fn format(r: Range, w: *Writer) Writer.Error!void { switch (r) { inline else => |range| try range.format(w), } }
/// Formats into `buffer`, returning the written slice. The buffer must be /// at least `max_text_len` bytes. pub fn bufPrint(r: Range, buffer: []u8) error{NoSpaceLeft}![]u8 { var w: Writer = .fixed(buffer); r.format(&w) catch return error.NoSpaceLeft; return w.buffered(); }
/// Writes the value as a JSON string. See `json.stringify`. pub fn jsonStringify(value: Range, 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, ) !Range { _ = options; return json.parse(Range, allocator, source); }
const testing = std.testing;
test init { const r = try Range.init(try .parse("10.0.0.1"), try .parse("10.0.0.9")); try testing.expect(r.first().eql(try .parse("10.0.0.1"))); const v6 = try Range.init(try .parse("2001:db8::1"), try .parse("2001:db8::9")); try testing.expect(v6.last().eql(try .parse("2001:db8::9"))); try testing.expectError( error.MixedFamilies, Range.init(try .parse("2001:db8::1"), try .parse("10.0.0.1")), ); // A range has two ends of one family, never one of each. try testing.expectError( error.MixedFamilies, Range.init(try .parse("10.0.0.1"), try .parse("2001:db8::1")), ); try testing.expectError( error.Inverted, Range.init(try .parse("10.0.0.9"), try .parse("10.0.0.1")), ); }
test fromNetwork { try testing.expect(Range.fromNetwork(try .parse("192.0.2.0/24")) .eql(try Range.parse("192.0.2.0-192.0.2.255"))); try testing.expect(Range.fromNetwork(try .parse("2001:db8::/120")) .eql(try Range.parse("2001:db8::-2001:db8::ff"))); }
test fromAddress { try testing.expect(Range.fromAddress(try .parse("10.0.0.1")).isSingleAddress()); try testing.expect(Range.fromAddress(try .parse("2001:db8::1")).isSingleAddress()); }
test parse { try testing.expect((try Range.parse("10.0.0.1-10.0.0.9")) == .ipv4); try testing.expect((try Range.parse("2001:db8::1-2001:db8::9")) == .ipv6); // Text holding a `:` is read as IPv6, so the error is the one that // version reports. try testing.expectError(error.MissingSeparator, Range.parse("10.0.0.1")); }
test isValid { try testing.expect(Range.isValid("10.0.0.1-10.0.0.9")); try testing.expect(!Range.isValid("10.0.0.9-10.0.0.1")); }
test family { try testing.expectEqual(.ipv4, (try Range.parse("10.0.0.1-10.0.0.9")).family()); try testing.expectEqual(.ipv6, (try Range.parse("::1-::9")).family()); }
test first { try testing.expect((try Range.parse("10.0.0.1-10.0.0.9")).first() .eql(try .parse("10.0.0.1"))); try testing.expect((try Range.parse("2001:db8::1-2001:db8::9")).first() .eql(try .parse("2001:db8::1"))); }
test last { try testing.expect((try Range.parse("10.0.0.1-10.0.0.9")).last() .eql(try .parse("10.0.0.9"))); try testing.expect((try Range.parse("2001:db8::1-2001:db8::9")).last() .eql(try .parse("2001:db8::9"))); }
test addressCount { try testing.expectEqual(@as(u129, 9), (try Range.parse("10.0.0.1-10.0.0.9")).addressCount()); // 129 bits wide, because an IPv6 range can cover the whole space. try testing.expectEqual( @as(u129, 1) << 128, (try Range.parse("::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")).addressCount(), ); }
test isSingleAddress { try testing.expect((try Range.parse("10.0.0.1-10.0.0.1")).isSingleAddress()); try testing.expect(!(try Range.parse("10.0.0.1-10.0.0.2")).isSingleAddress()); }
test contains { const r = try Range.parse("10.0.0.1-10.0.0.9"); try testing.expect(r.contains(try .parse("10.0.0.5"))); try testing.expect(!r.contains(try .parse("10.0.0.10"))); // An address of the other version is never in it. try testing.expect(!r.contains(try .parse("::1")));
const v6 = try Range.parse("2001:db8::1-2001:db8::9"); try testing.expect(v6.contains(try .parse("2001:db8::5"))); try testing.expect(!v6.contains(try .parse("2001:db8::a"))); try testing.expect(!v6.contains(try .parse("10.0.0.5"))); }
test containsRange { const outer = try Range.parse("10.0.0.1-10.0.0.9"); try testing.expect(outer.containsRange(try Range.parse("10.0.0.2-10.0.0.3"))); try testing.expect(!outer.containsRange(try Range.parse("2001:db8::1-2001:db8::2")));
const v6 = try Range.parse("2001:db8::1-2001:db8::9"); try testing.expect(v6.containsRange(try Range.parse("2001:db8::2-2001:db8::3"))); try testing.expect(!v6.containsRange(try Range.parse("10.0.0.1-10.0.0.2"))); }
test overlaps { const r = try Range.parse("10.0.0.1-10.0.0.9"); try testing.expect(r.overlaps(try Range.parse("10.0.0.9-10.0.0.20"))); try testing.expect(!r.overlaps(try Range.parse("10.0.0.10-10.0.0.20"))); try testing.expect(!r.overlaps(try Range.parse("::1-::9")));
const v6 = try Range.parse("2001:db8::1-2001:db8::9"); try testing.expect(v6.overlaps(try Range.parse("2001:db8::9-2001:db8::20"))); try testing.expect(!v6.overlaps(try Range.parse("2001:db8::a-2001:db8::20"))); try testing.expect(!v6.overlaps(try Range.parse("10.0.0.1-10.0.0.9"))); }
test toNetwork { try testing.expect((try Range.parse("192.0.2.0-192.0.2.255")).toNetwork().? .eql(try .parse("192.0.2.0/24"))); try testing.expectEqual(null, (try Range.parse("10.0.0.10-10.0.0.20")).toNetwork()); try testing.expect((try Range.parse("2001:db8::-2001:db8::ff")).toNetwork().? .eql(try .parse("2001:db8::/120"))); try testing.expectEqual(null, (try Range.parse("2001:db8::a-2001:db8::14")).toNetwork()); }
test prefixes { var it = (try Range.parse("2001:db8::-2001:db8::ff")).prefixes(); try testing.expect(it.next().?.eql(try .parse("2001:db8::/120"))); try testing.expectEqual(null, it.next()); }
test addresses { var it = (try Range.parse("10.0.0.1-10.0.0.3")).addresses(); var count: usize = 0; while (it.next()) |_| count += 1; try testing.expectEqual(@as(usize, 3), count); }
test merge { // Each version folds on its own, and IPv4 comes back first. var list = [_]Range{ try .parse("2001:db8::6-2001:db8::9"), try .parse("10.0.0.6-10.0.0.9"), try .parse("2001:db8::1-2001:db8::5"), try .parse("10.0.0.1-10.0.0.5"), }; const merged = Range.merge(&list); try testing.expectEqual(@as(usize, 2), merged.len); try testing.expect(merged[0].eql(try .parse("10.0.0.1-10.0.0.9"))); try testing.expect(merged[1].eql(try .parse("2001:db8::1-2001:db8::9"))); }
test lessThan { try testing.expect(lessThan({}, try .parse("10.0.0.1-10.0.0.5"), try .parse("::1-::9"))); try testing.expect(!lessThan({}, try .parse("::1-::9"), try .parse("10.0.0.1-10.0.0.5"))); }
test join { try testing.expect(Range.join( try .parse("10.0.0.1-10.0.0.5"), try .parse("10.0.0.6-10.0.0.9"), ).?.eql(try .parse("10.0.0.1-10.0.0.9"))); // Nothing joins across the versions, whatever the numbers look like. try testing.expectEqual(null, Range.join( try .parse("10.0.0.1-10.0.0.5"), try .parse("::1-::9"), )); }
test eql { try testing.expect((try Range.parse("10.0.0.1-10.0.0.9")) .eql(try Range.parse("10.0.0.1-10.0.0.9"))); // The versions are separate spaces, so these are never equal. try testing.expect(!(try Range.parse("10.0.0.1-10.0.0.9")) .eql(try Range.parse("::1-::9"))); }
test order { try testing.expectEqual(.lt, (try Range.parse("10.0.0.1-10.0.0.9")) .order(try Range.parse("::1-::9"))); try testing.expectEqual(.eq, (try Range.parse("10.0.0.1-10.0.0.9")) .order(try Range.parse("10.0.0.1-10.0.0.9"))); // Every IPv6 range sorts after every IPv4 one, and within a version // the low end decides first. try testing.expectEqual(.gt, (try Range.parse("::1-::9")) .order(try Range.parse("10.0.0.1-10.0.0.9"))); try testing.expectEqual(.lt, (try Range.parse("2001:db8::1-2001:db8::9")) .order(try Range.parse("2001:db8::2-2001:db8::9"))); }
test jsonStringify { // Driven directly, for the same reason `jsonParse` below is: // `std.json.Stringify.value` reflects over the type it is handed, and // fifteen copies of that is more than kcov will trace. Handing the hook a // `Stringify` tests the function this test is named after, and the one // instantiation it does need -- writing a `[]const u8` -- is shared by // every type here. var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); var jws: std.json.Stringify = .{ .writer = &w }; try (try Range.parse("10.0.0.10-10.0.0.20")).jsonStringify(&jws); // A JSON string holding exactly what `format` would have written. try testing.expectEqualStrings("\"10.0.0.10-10.0.0.20\"", 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, "\"10.0.0.10-10.0.0.20\""); defer scanner.deinit(); const value = try Range.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Range.parse("10.0.0.10-10.0.0.20")));
// 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, "\"10.0.0.20-10.0.0.10\""); defer bad.deinit(); try testing.expectError( error.InvalidCharacter, Range.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, Range.jsonParse(testing.allocator, &number, .{}), ); }
test format { var buffer: [Range.max_text_len]u8 = undefined; var w: Writer = .fixed(&buffer); try (try Range.parse("2001:db8::1-2001:db8::9")).format(&w); try testing.expectEqualStrings("2001:db8::1-2001:db8::9", w.buffered()); }
test bufPrint { var buffer: [Range.max_text_len]u8 = undefined; try testing.expectEqualStrings( "10.0.0.1-10.0.0.9", try (try Range.parse("10.0.0.1-10.0.0.9")).bufPrint(&buffer), ); }};