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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An IP address paired with a port, 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 Ipv4Endpoint = @import("Ipv4Endpoint.zig");const Ipv6Endpoint = @import("Ipv6Endpoint.zig");const sockaddr = @import("sockaddr.zig");
/// An `address:port` pair of either version, for code that handles both/// without caring which it has.pub const Endpoint = union(Family) { ipv4: Ipv4Endpoint, ipv6: Ipv6Endpoint,
pub const ParseError = Ipv4Endpoint.ParseError || Ipv6Endpoint.ParseError;
/// Parses an endpoint of either version, as written in a URL authority: /// `192.0.2.1:443` for IPv4 and `[2001:db8::1]:443` for IPv6. /// /// Bracketed text is read as IPv6 and everything else as IPv4. Text with /// more than one `:` and no brackets is `error.MissingBrackets` rather /// than an IPv4 error, since an unbracketed IPv6 address is exactly the /// ambiguity the brackets exist to resolve. pub fn parse(text: []const u8) ParseError!Endpoint { if (text.len != 0 and (text[0] == '[' or text[text.len - 1] == ']')) { return .{ .ipv6 = try .parse(text) }; } if (std.mem.count(u8, text, ":") > 1) return error.MissingBrackets; return .{ .ipv4 = try .parse(text) }; }
/// Whether `text` is a valid endpoint 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 port, choosing the endpoint type to match. pub fn init(value: Address, number: u16) Endpoint { return switch (value) { .ipv4 => |v4| .{ .ipv4 = .init(v4, number) }, .ipv6 => |v6| .{ .ipv6 = .init(v6, number) }, }; }
pub fn family(e: Endpoint) Family { return e; }
/// The address half, without the port. pub fn address(e: Endpoint) Address { return switch (e) { .ipv4 => |v4| .{ .ipv4 = v4.address }, .ipv6 => |v6| .{ .ipv6 = v6.address }, }; }
/// The port half. pub fn port(e: Endpoint) u16 { return switch (e) { inline else => |endpoint| endpoint.port, }; }
/// The longest text an endpoint of either version can format to. pub const max_text_len = @max(Ipv4Endpoint.max_text_len, Ipv6Endpoint.max_text_len);
/// Writes the endpoint in the form its version uses, bracketing an IPv6 /// address. Use the `{f}` specifier. pub fn format(e: Endpoint, w: *Writer) Writer.Error!void { switch (e) { inline else => |endpoint| try endpoint.format(w), } }
/// Formats into `buffer`, returning the written slice. The buffer must be /// at least `max_text_len` bytes. pub fn bufPrint(e: Endpoint, buffer: []u8) error{NoSpaceLeft}![]u8 { var w: Writer = .fixed(buffer); e.format(&w) catch return error.NoSpaceLeft; return w.buffered(); }
pub fn eql(e: Endpoint, other: Endpoint) bool { return switch (e) { .ipv4 => |v4| other == .ipv4 and v4.eql(other.ipv4), .ipv6 => |v6| other == .ipv6 and v6.eql(other.ipv6), }; }
/// Orders two endpoints, with every IPv4 endpoint before every IPv6 one. pub fn order(e: Endpoint, other: Endpoint) std.math.Order { return switch (e) { .ipv4 => |v4| switch (other) { .ipv4 => |o| v4.order(o), .ipv6 => .lt, }, .ipv6 => |v6| switch (other) { .ipv4 => .gt, .ipv6 => |o| v6.order(o), }, }; }
/// Converts to the standard library's socket address type. pub fn toStdAddress(e: Endpoint) std.Io.net.IpAddress { return switch (e) { .ipv4 => |v4| .{ .ip4 = v4.toStdAddress() }, .ipv6 => |v6| .{ .ip6 = v6.toStdAddress() }, }; }
/// Converts from the standard library's socket address type. pub fn fromStdAddress(a: std.Io.net.IpAddress) Endpoint { return switch (a) { .ip4 => |v4| .{ .ipv4 = .fromStdAddress(v4) }, .ip6 => |v6| .{ .ipv6 = .fromStdAddress(v6) }, }; }
/// What reading an endpoint out of a socket address structure can fail on. pub const SockaddrError = sockaddr.Error; /// The `sockaddr_in6` fields an address and a port do not account for. /// They are ignored for an IPv4 endpoint, which has no such fields. pub const SockaddrOptions = sockaddr.Options;
/// Fills in the socket address structure the version calls for, returning /// the number of bytes written: the `socklen_t` that goes with the /// pointer. /// /// The version is not known until run time, so the pointer has to be to /// something that can hold either: a `sockaddr` or a `sockaddr.storage`, /// from `std.posix`, `std.c` or `std.os.linux` alike. A pointer to a /// `sockaddr.in` or a `sockaddr.in6` has already settled the version, and /// is a compile error here; switch on the union and go through /// `Ipv4Endpoint` or `Ipv6Endpoint` to write into one of those. /// /// ``` /// var storage: std.posix.sockaddr.storage = undefined; /// const len = (try Endpoint.parse("[2001:db8::1]:443")).writeSockaddr(&storage); /// try std.posix.connect(fd, @ptrCast(&storage), len); /// ``` pub fn writeSockaddr(e: Endpoint, sa: anytype) u32 { return sockaddr.writeAddress(e.address(), e.port(), .{}, sa); }
/// Like `writeSockaddr`, but also setting the two fields that only an IPv6 /// structure has: the interface a link-local address is scoped to, and the /// flow label. Both are ignored for an IPv4 endpoint. pub fn writeSockaddrWithOptions(e: Endpoint, sa: anytype, options: SockaddrOptions) u32 { return sockaddr.writeAddress(e.address(), e.port(), options, sa); }
/// Reads an endpoint back out of a socket address structure of either /// version. /// /// A pointer to a `sockaddr.in` or a `sockaddr.in6` has already settled /// the version, and its `family` is checked against the one that type /// declares; a pointer to a `sockaddr` or a `sockaddr.storage` is read as /// whichever version its `family` names, and is /// `error.UnexpectedAddressFamily` when it names neither. pub fn fromSockaddr(sa: anytype) SockaddrError!Endpoint { return sockaddr.readEndpoint(sa); }
/// Writes the value as a JSON string. See `json.stringify`. pub fn jsonStringify(value: Endpoint, 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, ) !Endpoint { _ = options; return json.parse(Endpoint, allocator, source); }
test parse { try testing.expect((try Endpoint.parse("192.0.2.1:443")) == .ipv4); try testing.expect((try Endpoint.parse("[2001:db8::1]:443")) == .ipv6); // Without brackets the port's colon cannot be told from the address's, // which is reported as the missing brackets rather than as bad IPv4. try testing.expectError(error.MissingBrackets, Endpoint.parse("2001:db8::1:443")); try testing.expectError(error.MissingPort, Endpoint.parse("192.0.2.1")); }
test isValid { try testing.expect(Endpoint.isValid("192.0.2.1:443")); try testing.expect(Endpoint.isValid("[::1]:443")); try testing.expect(!Endpoint.isValid("::1:443")); }
test init { const e = Endpoint.init(try .parse("2001:db8::1"), 443); try testing.expect(e.eql(try Endpoint.parse("[2001:db8::1]:443"))); // The endpoint type follows the address's version. try testing.expect(Endpoint.init(try .parse("192.0.2.1"), 443) == .ipv4); }
test family { try testing.expectEqual(.ipv4, (try Endpoint.parse("192.0.2.1:443")).family()); try testing.expectEqual(.ipv6, (try Endpoint.parse("[::1]:443")).family()); }
test address { const e = try Endpoint.parse("[2001:db8::1]:443"); // The address half is the same value the address parser produces, so // everything that takes an address takes it. try testing.expect(e.address().eql(try .parse("2001:db8::1"))); try testing.expect(e.address().isDocumentation()); }
test port { try testing.expectEqual(@as(u16, 443), (try Endpoint.parse("192.0.2.1:443")).port()); try testing.expectEqual(@as(u16, 0), (try Endpoint.parse("[::]:0")).port()); }
test jsonStringify { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try std.json.Stringify.value(try Endpoint.parse("[2001:db8::1]:443"), .{}, &w); // A JSON string holding exactly what `format` would have written. try testing.expectEqualStrings("\"[2001:db8::1]:443\"", 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, "\"[2001:db8::1]:443\""); defer scanner.deinit(); const value = try Endpoint.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Endpoint.parse("[2001:db8::1]:443")));
// 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:443\""); defer bad.deinit(); try testing.expectError( error.InvalidCharacter, Endpoint.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, Endpoint.jsonParse(testing.allocator, &number, .{}), ); }
test format { try testing.expectFmt("192.0.2.1:443", "{f}", .{try Endpoint.parse("192.0.2.1:443")}); // An IPv6 address keeps the brackets that make the port readable. try testing.expectFmt("[2001:db8::1]:443", "{f}", .{try Endpoint.parse("[2001:db8::1]:443")}); }
test bufPrint { var buffer: [Endpoint.max_text_len]u8 = undefined; try testing.expectEqualStrings("[::1]:80", try (try Endpoint.parse("[::1]:80")).bufPrint(&buffer));
var small: [4]u8 = undefined; try testing.expectError(error.NoSpaceLeft, (try Endpoint.parse("[::1]:80")).bufPrint(&small)); }
test eql { try testing.expect((try Endpoint.parse("[::1]:80")).eql(try Endpoint.parse("[0:0::1]:80"))); // The two versions are never equal, however alike the text looks. try testing.expect(!(try Endpoint.parse("192.0.2.1:443")) .eql(try Endpoint.parse("[::ffff:192.0.2.1]:443"))); }
test order { // Every IPv4 endpoint sorts before every IPv6 one, and within a // version the address decides before the port. try testing.expectEqual(.lt, (try Endpoint.parse("255.255.255.255:65535")) .order(try Endpoint.parse("[::]:0"))); try testing.expectEqual(.lt, (try Endpoint.parse("192.0.2.1:80")) .order(try Endpoint.parse("192.0.2.1:443"))); try testing.expectEqual(.eq, (try Endpoint.parse("[::1]:80")) .order(try Endpoint.parse("[::1]:80"))); }
test toStdAddress { try testing.expect((try Endpoint.parse("192.0.2.1:443")).toStdAddress() == .ip4); const socket = (try Endpoint.parse("[2001:db8::1]:443")).toStdAddress(); try testing.expectEqual(@as(u16, 443), socket.ip6.port); }
test fromStdAddress { const e = try Endpoint.parse("[2001:db8::1]:443"); try testing.expect(e.eql(Endpoint.fromStdAddress(e.toStdAddress()))); }
test writeSockaddr { // The version is not known until run time, so the structure written // into has to be one that can hold either. var storage: std.posix.sockaddr.storage = undefined; const e = try Endpoint.parse("[2001:db8::1]:443"); const len = e.writeSockaddr(&storage); try testing.expectEqual(@as(u32, @sizeOf(std.posix.sockaddr.in6)), len); try testing.expect(e.eql(try Endpoint.fromSockaddr(&storage))); }
test writeSockaddrWithOptions { var storage: std.posix.sockaddr.storage = undefined; const e = try Endpoint.parse("[fe80::1]:22"); _ = e.writeSockaddrWithOptions(&storage, .{ .scope_id = 2 }); try testing.expectEqual(@as(u32, 2), (try Ipv6Endpoint.sockaddrOptions(&storage)).scope_id);
// Neither field exists on an IPv4 structure, so both are ignored there. const v4 = try Endpoint.parse("192.0.2.1:443"); _ = v4.writeSockaddrWithOptions(&storage, .{ .scope_id = 2 }); try testing.expect(v4.eql(try Endpoint.fromSockaddr(&storage))); }
test fromSockaddr { var storage: std.posix.sockaddr.storage = undefined; for ([_][]const u8{ "192.0.2.1:443", "[2001:db8::1]:443" }) |text| { const e = try Endpoint.parse(text); _ = e.writeSockaddr(&storage); try testing.expect(e.eql(try Endpoint.fromSockaddr(&storage))); }
// Any other family is reported rather than guessed at. storage.family = std.posix.AF.UNIX; try testing.expectError(error.UnexpectedAddressFamily, Endpoint.fromSockaddr(&storage)); }};
const testing = std.testing;
test "parse dispatches on version" { try testing.expect((try Endpoint.parse("192.0.2.1:443")) == .ipv4); try testing.expect((try Endpoint.parse("[2001:db8::1]:443")) == .ipv6); try testing.expect((try Endpoint.parse("[::1]:80")) == .ipv6); try testing.expectEqual(.ipv6, (try Endpoint.parse("[::1]:80")).family());
// An unbracketed IPv6 address is the ambiguity the brackets resolve, so it // is reported as a missing bracket rather than as a bad IPv4 address. try testing.expectError(error.MissingBrackets, Endpoint.parse("2001:db8::1:443")); try testing.expectError(error.MissingBrackets, Endpoint.parse("::1:443")); // A stray closing bracket mid-text is the same mistake: the address was // never bracketed, so the port cannot be told from the address. try testing.expectError(error.MissingBrackets, Endpoint.parse("2001:db8::1]:443")); // An opened bracket that is never closed is a different mistake. try testing.expectError(error.UnmatchedBracket, Endpoint.parse("[::1:443"));
// A single colon is an IPv4 endpoint, well formed or not. try testing.expectError(error.MissingPort, Endpoint.parse("192.0.2.1")); try testing.expectError(error.OctetOutOfRange, Endpoint.parse("192.0.2.256:443")); try testing.expectError(error.PortOutOfRange, Endpoint.parse("192.0.2.1:99999"));
try testing.expect(Endpoint.isValid("192.0.2.1:443")); try testing.expect(Endpoint.isValid("[::1]:443")); try testing.expect(!Endpoint.isValid("::1:443"));}
test "parts and construction" { const e = try Endpoint.parse("[2001:db8::1]:443"); try testing.expect(e.address().eql(try .parse("2001:db8::1"))); try testing.expectEqual(@as(u16, 443), e.port()); try testing.expect(e.eql(Endpoint.init(try .parse("2001:db8::1"), 443)));
const v4 = try Endpoint.parse("192.0.2.1:80"); try testing.expect(v4.address().eql(try .parse("192.0.2.1"))); try testing.expect(v4.eql(Endpoint.init(try .parse("192.0.2.1"), 80)));
// The address half keeps its own classification predicates. try testing.expect((try Endpoint.parse("127.0.0.1:8080")).address().isLoopback());}
test "format and ordering" { try testing.expectFmt("192.0.2.1:443", "{f}", .{try Endpoint.parse("192.0.2.1:443")}); try testing.expectFmt("[2001:db8::1]:443", "{f}", .{try Endpoint.parse("[2001:db8::1]:443")});
var buffer: [Endpoint.max_text_len]u8 = undefined; try testing.expectEqualStrings("[::1]:80", try (try Endpoint.parse("[::1]:80")).bufPrint(&buffer));
try testing.expectEqual(.lt, (try Endpoint.parse("255.255.255.255:65535")) .order(try Endpoint.parse("[::]:0"))); try testing.expectEqual(.lt, (try Endpoint.parse("192.0.2.1:80")) .order(try Endpoint.parse("192.0.2.1:443"))); try testing.expect(!(try Endpoint.parse("192.0.2.1:443")) .eql(try Endpoint.parse("[::ffff:192.0.2.1]:443")));}
test "interoperating with std.Io.net" { for ([_][]const u8{ "192.0.2.1:443", "[2001:db8::1]:443" }) |text| { const e = try Endpoint.parse(text); try testing.expect(e.eql(Endpoint.fromStdAddress(e.toStdAddress()))); }}