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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An IPv4 address paired with a port, as in `192.0.2.1:443`.
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 port_parser = @import("port.zig");const sockaddr = @import("sockaddr.zig");
const Ipv4Endpoint = @This();
address: Ipv4Address,port: u16,
pub fn init(address: Ipv4Address, port: u16) Ipv4Endpoint { return .{ .address = address, .port = port };}
pub const ParseError = Ipv4Address.ParseError || port_parser.ParseError || error{ /// The text held no `:`, so there was no port to read. MissingPort,};
/// Parses `address:port`, as in `192.0.2.1:443`.////// Both halves are parsed as strictly as they are on their own: no shorthand/// address forms, and no leading zeros in either an octet or the port.pub fn parse(text: []const u8) ParseError!Ipv4Endpoint { const colon = std.mem.findScalar(u8, text, ':') orelse return error.MissingPort; return .{ .address = try Ipv4Address.parse(text[0..colon]), .port = try port_parser.parse(text[colon + 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 IPv4 endpoint can format to, as in/// `255.255.255.255:65535`.pub const max_text_len = Ipv4Address.max_text_len + ":".len + port_parser.max_text_len;
/// Writes `address:port`. Use the `{f}` specifier.pub fn format(e: Ipv4Endpoint, 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: Ipv4Endpoint, 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 byte of slack the address's `bufPrint`/// wants to render in place and the spill of `decimal.render`.const render_len = Ipv4Address.max_text_len + 1 + ":".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: Ipv4Endpoint, buffer: *[render_len]u8) []u8 { const address = e.address.bufPrint(buffer[0 .. Ipv4Address.max_text_len + 1]) catch unreachable; var len = address.len; buffer[len] = ':'; len += 1; len += decimal.render(e.port, buffer[len..][0..8]); return buffer[0..len];}
pub fn eql(e: Ipv4Endpoint, other: Ipv4Endpoint) bool { return e.port == other.port and e.address.eql(other.address);}
/// Orders by address first, then by port.pub fn order(e: Ipv4Endpoint, other: Ipv4Endpoint) 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, which is the same/// pairing of address and port.pub fn toStdAddress(e: Ipv4Endpoint) std.Io.net.Ip4Address { return .{ .bytes = e.address.octets, .port = e.port };}
/// Converts from the standard library's socket address type.pub fn fromStdAddress(a: std.Io.net.Ip4Address) Ipv4Endpoint { 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;
/// Fills in a `sockaddr_in` 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.in`, or to a `sockaddr` or a/// `sockaddr.storage` standing in for one, and may come from `std.posix`,/// `std.c` or `std.os.linux` alike.////// ```/// var storage: std.posix.sockaddr.storage = undefined;/// const len = (try Ipv4Endpoint.parse("192.0.2.1:443")).writeSockaddr(&storage);/// try std.posix.connect(fd, @ptrCast(&storage), len);/// ```pub fn writeSockaddr(e: Ipv4Endpoint, sa: anytype) u32 { return sockaddr.writeIpv4(e.address, e.port, sa);}
/// Reads an endpoint back out of a `sockaddr_in`.////// `error.UnexpectedAddressFamily` when the structure's `family` is not/// `AF_INET`, which is the only thing about it that can be wrong.pub fn fromSockaddr(sa: anytype) SockaddrError!Ipv4Endpoint { return sockaddr.readIpv4(sa);}
/// Writes the value as a JSON string. See `json.stringify`.pub fn jsonStringify(value: Ipv4Endpoint, 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,) !Ipv4Endpoint { _ = options; return json.parse(Ipv4Endpoint, allocator, source);}
const testing = std.testing;
test parse { const e = try parse("192.0.2.1:443"); try testing.expectEqual(Ipv4Address.init(192, 0, 2, 1), e.address); try testing.expectEqual(@as(u16, 443), e.port);
try testing.expect((try parse("0.0.0.0:0")).eql(init(.unspecified, 0))); try testing.expect((try parse("255.255.255.255:65535")).eql(init(.broadcast, 65535)));}
test "parse rejects malformed text" { try testing.expectError(error.MissingPort, parse("192.0.2.1")); try testing.expectError(error.EmptyPort, parse("192.0.2.1:")); try testing.expectError(error.PortOutOfRange, parse("192.0.2.1:65536")); try testing.expectError(error.LeadingZero, parse("192.0.2.1:0443")); try testing.expectError(error.InvalidPort, parse("192.0.2.1:443:80")); try testing.expectError(error.InvalidPort, parse("192.0.2.1:http")); try testing.expectError(error.EmptyOctet, parse(":443")); try testing.expectError(error.TooFewOctets, parse("192.0.2:443")); try testing.expectError(error.LeadingZero, parse("192.0.02.1:443")); // An IPv6 address is not an IPv4 endpoint, however it is written. try testing.expectError(error.InvalidCharacter, parse("[::1]:443"));
try testing.expect(isValid("192.0.2.1:443")); try testing.expect(!isValid("192.0.2.1"));}
test jsonStringify { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try std.json.Stringify.value(try Ipv4Endpoint.parse("192.0.2.1:443"), .{}, &w); // A JSON string holding exactly what `format` would have written. try testing.expectEqualStrings("\"192.0.2.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, "\"192.0.2.1:443\""); defer scanner.deinit(); const value = try Ipv4Endpoint.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Ipv4Endpoint.parse("192.0.2.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, "\"192.0.2.1\""); defer bad.deinit(); try testing.expectError( error.InvalidCharacter, Ipv4Endpoint.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, Ipv4Endpoint.jsonParse(testing.allocator, &number, .{}), );}
test format { try testing.expectFmt("192.0.2.1:443", "{f}", .{try parse("192.0.2.1:443")}); try testing.expectFmt("0.0.0.0:0", "{f}", .{init(.unspecified, 0)});
var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings("255.255.255.255:65535", try (init(.broadcast, 65535)).bufPrint(&buffer));}
test "round trip through text" { const cases = [_][]const u8{ "0.0.0.0:0", "127.0.0.1:8080", "255.255.255.255: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.expect((try parse("192.0.2.1:443")).eql(init(.init(192, 0, 2, 1), 443))); try testing.expectEqual(.lt, (try parse("192.0.2.1:80")).order(try parse("192.0.2.1:443"))); try testing.expectEqual(.lt, (try parse("192.0.2.1:443")).order(try parse("192.0.2.2:80"))); try testing.expectEqual(.eq, (try parse("192.0.2.1:443")).order(try parse("192.0.2.1:443")));}
test "interoperating with std.Io.net" { const e = try parse("192.0.2.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: Ipv4Endpoint = .init(.init(192, 0, 2, 1), 443); try testing.expect(e.eql(try parse("192.0.2.1:443")));}
test isValid { try testing.expect(isValid("192.0.2.1:443")); // A port is part of an endpoint, so an address on its own is not one. try testing.expect(!isValid("192.0.2.1")); try testing.expect(!isValid("192.0.2.1:65536"));}
test bufPrint { var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings("192.0.2.1:443", try (try parse("192.0.2.1:443")).bufPrint(&buffer));
var small: [4]u8 = undefined; try testing.expectError(error.NoSpaceLeft, (try parse("192.0.2.1:443")).bufPrint(&small));}
test eql { try testing.expect((try parse("192.0.2.1:443")).eql(.init(.init(192, 0, 2, 1), 443))); // Both halves have to match. try testing.expect(!(try parse("192.0.2.1:443")).eql(try parse("192.0.2.1:80"))); try testing.expect(!(try parse("192.0.2.1:443")).eql(try parse("192.0.2.2:443")));}
test order { // The address decides first, and the port only breaks a tie on it. try testing.expectEqual(.lt, (try parse("192.0.2.1:443")).order(try parse("192.0.2.2:80"))); try testing.expectEqual(.lt, (try parse("192.0.2.1:80")).order(try parse("192.0.2.1:443"))); try testing.expectEqual(.eq, (try parse("192.0.2.1:443")).order(try parse("192.0.2.1:443")));}
test toStdAddress { const socket = (try parse("192.0.2.1:443")).toStdAddress(); try testing.expectEqualSlices(u8, &.{ 192, 0, 2, 1 }, &socket.bytes); try testing.expectEqual(@as(u16, 443), socket.port);}
test fromStdAddress { const e = fromStdAddress(.{ .bytes = .{ 192, 0, 2, 1 }, .port = 443 }); try testing.expect(e.eql(try parse("192.0.2.1:443")));}
test writeSockaddr { var storage: std.posix.sockaddr.storage = undefined; const e = try parse("192.0.2.1:443"); const len = e.writeSockaddr(&storage); try testing.expectEqual(@as(u32, @sizeOf(std.posix.sockaddr.in)), len); try testing.expect(e.eql(try fromSockaddr(&storage)));}
test fromSockaddr { var sa: std.posix.sockaddr.in = undefined; const e = try parse("192.0.2.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.INET6; try testing.expectError(error.UnexpectedAddressFamily, fromSockaddr(&sa));}
test render { // The one place the text is produced; `format` and `bufPrint` both go // through it. The buffer carries slack for the address's own spill and for // the port. var buffer: [render_len]u8 = undefined; try testing.expectEqualStrings("192.0.2.1:443", (try parse("192.0.2.1:443")).render(&buffer)); try testing.expectEqualStrings("0.0.0.0:0", (Ipv4Endpoint.init(.unspecified, 0)).render(&buffer)); try testing.expectEqualStrings( "255.255.255.255:65535", (Ipv4Endpoint.init(.broadcast, 65535)).render(&buffer), );}