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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An IPv6 address paired with a port, as in `[2001:db8::1]:443`.//!//! The brackets are part of the notation rather than decoration: without them//! the `:` before the port could not be told from the colons inside the//! address (RFC 3986).
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 port_parser = @import("port.zig");const sockaddr = @import("sockaddr.zig");
const Ipv6Endpoint = @This();
address: Ipv6Address,port: u16,
pub fn init(address: Ipv6Address, port: u16) Ipv6Endpoint { return .{ .address = address, .port = port };}
pub const ParseError = Ipv6Address.ParseError || port_parser.ParseError || error{ /// The text held no `:port` after the address. MissingPort, /// The address was not wrapped in square brackets. They are required here, /// because `::1:443` could be read either as an address with a port or as /// an address on its own. MissingBrackets,};
/// Parses `[address]:port`, as in `[2001:db8::1]:443`.////// A zone identifier is rejected, as it is by `Ipv6Address.parse`; text/// carrying one has to go through `Ipv6Address.parseZonedWithOptions`.pub fn parse(text: []const u8) ParseError!Ipv6Endpoint { if (text.len == 0 or text[0] != '[') return error.MissingBrackets; const close = std.mem.findScalar(u8, text, ']') orelse return error.UnmatchedBracket; const address = try Ipv6Address.parseWithOptions(text[0 .. close + 1], .{ .allow_brackets = true }); const rest = text[close + 1 ..]; if (rest.len == 0 or rest[0] != ':') return error.MissingPort; return .{ .address = address, .port = try port_parser.parse(rest[1..]) };}
/// Whether `text` is a valid `[address]:port`, discarding the reason when it/// is not.pub fn isValid(text: []const u8) bool { _ = parse(text) catch return false; return true;}
/// The longest text an IPv6 endpoint can format to.pub const max_text_len = "[]:".len + Ipv6Address.max_text_len + port_parser.max_text_len;
/// Writes `[address]:port`, with the address in its canonical form. Use the/// `{f}` specifier.pub fn format(e: Ipv6Endpoint, w: *Writer) Writer.Error!void { var buffer: [render_len]u8 = undefined; try w.writeAll(e.render(&buffer));}
/// Formats into `buffer`, returning the written slice. The buffer must be at/// least `max_text_len` bytes.pub fn bufPrint(e: Ipv6Endpoint, buffer: []u8) error{NoSpaceLeft}![]u8 { var rendered: [render_len]u8 = undefined; const text = e.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.render`.const render_len = "[".len + Ipv6Address.max_text_len + "]:".len + 8;
/// Renders `[address]:port` 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 endpoint.fn render(e: Ipv6Endpoint, buffer: *[render_len]u8) []u8 { buffer[0] = '['; const address = e.address.bufPrint(buffer[1..][0..Ipv6Address.max_text_len]) catch unreachable; var len = 1 + address.len; buffer[len..][0..2].* = "]:".*; len += 2; len += decimal.render(e.port, buffer[len..][0..8]); return buffer[0..len];}
pub fn eql(e: Ipv6Endpoint, other: Ipv6Endpoint) bool { return e.port == other.port and e.address.eql(other.address);}
/// Orders by address first, then by port.pub fn order(e: Ipv6Endpoint, other: Ipv6Endpoint) std.math.Order { return switch (e.address.order(other.address)) { .eq => std.math.order(e.port, other.port), else => |result| result, };}
/// Converts to the standard library's socket address type, leaving its flow/// label and interface unset.pub fn toStdAddress(e: Ipv6Endpoint) std.Io.net.Ip6Address { return .{ .bytes = e.address.octets, .port = e.port };}
/// Converts from the standard library's socket address type, dropping its flow/// label and interface.pub fn fromStdAddress(a: std.Io.net.Ip6Address) Ipv6Endpoint { return .{ .address = .{ .octets = a.bytes }, .port = a.port };}
/// 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.pub const SockaddrOptions = sockaddr.Options;
/// Fills in a `sockaddr_in6` through a pointer to one, returning the number of/// bytes written: the `socklen_t` that goes with the pointer.////// The pointer may be to a `sockaddr.in6`, or to a `sockaddr` or a/// `sockaddr.storage` large enough to hold one, and may come from `std.posix`,/// `std.c` or `std.os.linux` alike. The whole structure is written, which/// leaves the flow label and the scope identifier zero; use/// `writeSockaddrWithOptions` for a link-local address, which means nothing/// without the interface it is scoped to.pub fn writeSockaddr(e: Ipv6Endpoint, sa: anytype) u32 { return sockaddr.writeIpv6(e.address, e.port, .{}, sa);}
/// Like `writeSockaddr`, but also setting the interface a link-local address/// is scoped to and the flow label.pub fn writeSockaddrWithOptions(e: Ipv6Endpoint, sa: anytype, options: SockaddrOptions) u32 { return sockaddr.writeIpv6(e.address, e.port, options, sa);}
/// Reads an endpoint back out of a `sockaddr_in6`, dropping its flow label and/// scope identifier. `sockaddrOptions` returns those.////// `error.UnexpectedAddressFamily` when the structure's `family` is not/// `AF_INET6`.pub fn fromSockaddr(sa: anytype) SockaddrError!Ipv6Endpoint { return sockaddr.readIpv6(sa);}
/// The flow label and scope identifier a `sockaddr_in6` carries, which an/// endpoint has nowhere to keep.pub fn sockaddrOptions(sa: anytype) SockaddrError!SockaddrOptions { return sockaddr.readIpv6Options(sa);}
/// Writes the value as a JSON string. See `json.stringify`.pub fn jsonStringify(value: Ipv6Endpoint, 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,) !Ipv6Endpoint { _ = options; return json.parse(Ipv6Endpoint, allocator, source);}
const testing = std.testing;
test parse { const e = try parse("[2001:db8::1]:443"); try testing.expectEqual(try Ipv6Address.parse("2001:db8::1"), e.address); try testing.expectEqual(@as(u16, 443), e.port);
try testing.expect((try parse("[::1]:8080")).eql(init(.loopback, 8080))); try testing.expect((try parse("[::]:0")).eql(init(.unspecified, 0))); try testing.expect((try parse("[::ffff:192.0.2.1]:443")) .eql(init(try .parse("::ffff:192.0.2.1"), 443)));}
test "parse rejects malformed text" { // The brackets are required, so a bare address is never an endpoint. try testing.expectError(error.MissingBrackets, parse("2001:db8::1")); try testing.expectError(error.MissingBrackets, parse("::1:443")); try testing.expectError(error.MissingBrackets, parse(""));
try testing.expectError(error.UnmatchedBracket, parse("[::1:443")); try testing.expectError(error.MissingPort, parse("[::1]")); try testing.expectError(error.MissingPort, parse("[::1]443")); try testing.expectError(error.EmptyPort, parse("[::1]:")); try testing.expectError(error.PortOutOfRange, parse("[::1]:65536")); try testing.expectError(error.LeadingZero, parse("[::1]:0443")); try testing.expectError(error.TooFewGroups, parse("[]:443")); try testing.expectError(error.InvalidCharacter, parse("[::g]:443")); // A zone has to be handled by the address parser. try testing.expectError(error.UnexpectedZone, parse("[fe80::1%eth0]:443"));
try testing.expect(isValid("[::1]:443")); try testing.expect(!isValid("::1:443"));}
test jsonStringify { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try std.json.Stringify.value(try Ipv6Endpoint.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`, 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]:443\""); defer scanner.deinit(); const value = try Ipv6Endpoint.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Ipv6Endpoint.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, Ipv6Endpoint.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, Ipv6Endpoint.jsonParse(testing.allocator, &number, .{}), );}
test format { try testing.expectFmt("[2001:db8::1]:443", "{f}", .{try parse("[2001:db8::1]:443")}); try testing.expectFmt("[::1]:8080", "{f}", .{init(.loopback, 8080)}); // The address half is canonicalised the same way it is on its own. try testing.expectFmt("[2001:db8::1]:443", "{f}", .{try parse("[2001:0DB8:0:0:0:0:0:1]:443")});}
test "round trip through text" { const cases = [_][]const u8{ "[::]:0", "[::1]:8080", "[2001:db8::1]:443", "[::ffff:192.0.2.1]:443", "[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535", }; 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.expectEqual(.lt, (try parse("[::1]:80")).order(try parse("[::1]:443"))); try testing.expectEqual(.lt, (try parse("[::1]:443")).order(try parse("[::2]:80"))); try testing.expectEqual(.eq, (try parse("[::1]:443")).order(try parse("[::1]:443")));}
test "interoperating with std.Io.net" { const e = try parse("[2001:db8::1]:443"); const socket = e.toStdAddress(); try testing.expectEqual(@as(u16, 443), socket.port); try testing.expect(e.eql(fromStdAddress(socket)));}
test init { const e: Ipv6Endpoint = .init(try .parse("2001:db8::1"), 443); try testing.expect(e.eql(try parse("[2001:db8::1]:443")));}
test isValid { try testing.expect(isValid("[2001:db8::1]:443")); // The brackets are what tell the port's colon from the address's. try testing.expect(!isValid("2001:db8::1:443")); try testing.expect(!isValid("[2001:db8::1]"));}
test bufPrint { var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings( "[2001:db8::1]:443", try (try parse("[2001:db8::1]:443")).bufPrint(&buffer), );
var small: [4]u8 = undefined; try testing.expectError(error.NoSpaceLeft, (try parse("[::1]:80")).bufPrint(&small));}
test eql { try testing.expect((try parse("[::1]:80")).eql(.init(.loopback, 80))); // Both halves have to match. try testing.expect(!(try parse("[::1]:80")).eql(try parse("[::1]:443"))); try testing.expect(!(try parse("[::1]:80")).eql(try parse("[::2]:80")));}
test order { // The address decides first, and the port only breaks a tie on it. try testing.expectEqual(.lt, (try parse("[::1]:443")).order(try parse("[::2]:80"))); try testing.expectEqual(.lt, (try parse("[::1]:80")).order(try parse("[::1]:443"))); try testing.expectEqual(.eq, (try parse("[::1]:80")).order(try parse("[::1]:80")));}
test toStdAddress { const socket = (try parse("[2001:db8::1]:443")).toStdAddress(); try testing.expectEqual(@as(u16, 443), socket.port); try testing.expect(fromStdAddress(socket).eql(try parse("[2001:db8::1]:443")));}
test fromStdAddress { const e = fromStdAddress((try parse("[2001:db8::1]:443")).toStdAddress()); try testing.expect(e.eql(try parse("[2001:db8::1]:443")));}
test writeSockaddr { var storage: std.posix.sockaddr.storage = undefined; const e = try 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 fromSockaddr(&storage))); // The flow label and the scope are left at zero. try testing.expectEqual(SockaddrOptions{}, try sockaddrOptions(&storage));}
test writeSockaddrWithOptions { var sa: std.posix.sockaddr.in6 = undefined; // `fe80::1` means nothing without the interface it is scoped to. const e = try parse("[fe80::1]:22"); _ = e.writeSockaddrWithOptions(&sa, .{ .scope_id = 2 }); try testing.expectEqual(@as(u32, 2), sa.scope_id); try testing.expect(e.eql(try fromSockaddr(&sa)));}
test fromSockaddr { var sa: std.posix.sockaddr.in6 = undefined; const e = try parse("[2001:db8::1]:443"); _ = e.writeSockaddr(&sa); try testing.expect(e.eql(try fromSockaddr(&sa)));
// A structure of any other family is reported rather than misread. sa.family = std.posix.AF.INET; try testing.expectError(error.UnexpectedAddressFamily, fromSockaddr(&sa));}
test sockaddrOptions { var sa: std.posix.sockaddr.in6 = undefined; _ = (try parse("[fe80::1]:22")).writeSockaddrWithOptions(&sa, .{ .scope_id = 3, .flowinfo = 7 }); try testing.expectEqual( SockaddrOptions{ .scope_id = 3, .flowinfo = 7 }, try sockaddrOptions(&sa), );}
test render { // The one place the text is produced; `format` and `bufPrint` both go // through it. The brackets are part of the notation rather than decoration. var buffer: [render_len]u8 = undefined; try testing.expectEqualStrings("[2001:db8::1]:443", (try parse("[2001:db8::1]:443")).render(&buffer)); try testing.expectEqualStrings("[::]:0", (Ipv6Endpoint.init(.unspecified, 0)).render(&buffer)); try testing.expectEqualStrings( "[::ffff:192.0.2.1]:65535", (Ipv6Endpoint.init(try .parse("::ffff:192.0.2.1"), 65535)).render(&buffer), );}