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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Filling in and reading back the C socket address structures, given a//! pointer to one.//!//! `std.posix.sockaddr`, `std.c.sockaddr` and `std.os.linux.sockaddr` are one//! family of structures under three names, and nothing here names any of//! them. Every function takes the pointer as `anytype` and works out from its//! type which shape it points at — the `sockaddr_in` of an IPv4 address, the//! `sockaddr_in6` of an IPv6 one, or the family-agnostic `sockaddr` and//! `sockaddr_storage` that carry either — so the same call site compiles//! against whichever of the three namespaces the surrounding code already//! uses.//!//! The `AF_INET` and `AF_INET6` values come from the same namespace as the//! pointer, read off the defaults its own `in` and `in6` declarations give//! their `family` fields, rather than from the host's. That matters because//! `AF_INET6` is 10 on Linux, 30 on Darwin, 28 on FreeBSD and 23 on Windows://! a constant taken from the wrong one is wrong silently. The single//! exception is a pointer to a `sockaddr_storage`, which names no nested//! types to read a default from, so `std.posix` stands in.//!//! A `sockaddr` pointer says nothing about how much storage is really behind//! it — that is as true here as it is in C, because it is the same pointer.//! The structure written for an IPv6 address is 28 bytes where an IPv4 one is//! 16, so a `*sockaddr` written through must point at something large enough//! for the version being written; `sockaddr.storage` is the usual way to have//! that, and is what `accept` and `recvfrom` are given. A pointer to an `in`//! or an `in6` carries its own size and needs no such care.
const std = @import("std");
const Address = @import("address.zig").Address;const Endpoint = @import("endpoint.zig").Endpoint;const Ipv4Address = @import("Ipv4Address.zig");const Ipv4Endpoint = @import("Ipv4Endpoint.zig");const Ipv6Address = @import("Ipv6Address.zig");const Ipv6Endpoint = @import("Ipv6Endpoint.zig");
/// What reading a socket address structure can fail on.pub const Error = error{ /// The structure's `family` was not one the type being read accepts. UnexpectedAddressFamily,};
/// The two fields a `sockaddr_in6` has that an address and a port do not/// account for. Both are zero unless something has set them, which is what/// the plain `writeSockaddr` functions leave them as.pub const Options = struct { /// `sin6_scope_id`, the index of the interface that gives a link-local /// address its meaning. Zero is unscoped, which is right for every address /// outside `fe80::/10`. scope_id: u32 = 0, /// `sin6_flowinfo`, the flow label and traffic class. Zero unless a flow /// label has been assigned. flowinfo: u32 = 0,};
/// Fills in a `sockaddr_in`, returning the number of bytes written — the/// `socklen_t` that goes with the pointer.pub fn writeIpv4(address: Ipv4Address, port: u16, sa: anytype) u32 { const In = in(Pointee(@TypeOf(sa))); const value: In = .{ .port = std.mem.nativeToBig(u16, port), // `sin_addr` holds the four octets in the order they travel, which is // exactly their memory layout, so a bit cast is the whole conversion // on a host of either byte order. .addr = @bitCast(address.octets), }; return write(In, &value, sa);}
/// Fills in a `sockaddr_in6`, returning the number of bytes written.pub fn writeIpv6(address: Ipv6Address, port: u16, options: Options, sa: anytype) u32 { const In6 = in6(Pointee(@TypeOf(sa))); const value: In6 = .{ .port = std.mem.nativeToBig(u16, port), .flowinfo = std.mem.nativeToBig(u32, options.flowinfo), .addr = address.octets, // The scope identifier is an interface index rather than anything that // goes on the wire, so it stays in the host's byte order. .scope_id = options.scope_id, }; return write(In6, &value, sa);}
/// Fills in whichever structure the address calls for, returning the number of/// bytes written.////// Because the version is not known until run time, the pointer has to be to a/// structure that can hold either: a `sockaddr` or a `sockaddr_storage`, not/// an `in` or an `in6`. Switch on the value and call `writeIpv4` or/// `writeIpv6` to write into one of those.pub fn writeAddress(address: Address, port: u16, options: Options, sa: anytype) u32 { requireEitherVersion(Pointee(@TypeOf(sa))); return switch (address) { .ipv4 => |v4| writeIpv4(v4, port, sa), .ipv6 => |v6| writeIpv6(v6, port, options, sa), };}
/// Reads a `sockaddr_in` back as an address and a port.pub fn readIpv4(sa: anytype) Error!Ipv4Endpoint { const In = in(Pointee(@TypeOf(sa))); if (sa.family != familyOf(In)) return error.UnexpectedAddressFamily; const value = read(In, sa); return .{ .address = .{ .octets = @bitCast(value.addr) }, .port = std.mem.bigToNative(u16, value.port), };}
/// Reads a `sockaddr_in6` back as an address and a port, dropping its flow/// label and scope identifier. `readIpv6Options` returns those.pub fn readIpv6(sa: anytype) Error!Ipv6Endpoint { const In6 = in6(Pointee(@TypeOf(sa))); if (sa.family != familyOf(In6)) return error.UnexpectedAddressFamily; const value = read(In6, sa); return .{ .address = .{ .octets = value.addr }, .port = std.mem.bigToNative(u16, value.port), };}
/// The flow label and scope identifier a `sockaddr_in6` carries, which an/// `Ipv6Address` has nowhere to keep.pub fn readIpv6Options(sa: anytype) Error!Options { const In6 = in6(Pointee(@TypeOf(sa))); if (sa.family != familyOf(In6)) return error.UnexpectedAddressFamily; const value = read(In6, sa); return .{ .scope_id = value.scope_id, .flowinfo = std.mem.bigToNative(u32, value.flowinfo), };}
/// Reads back a structure of either version, deciding which by its `family`.////// A pointer to an `in` or an `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 of the two its/// `family` names, and is `error.UnexpectedAddressFamily` when it names/// neither.pub fn readEndpoint(sa: anytype) Error!Endpoint { const Target = Pointee(@TypeOf(sa)); return switch (comptime shapeOf(Target)) { .in => .{ .ipv4 = try readIpv4(sa) }, .in6 => .{ .ipv6 = try readIpv6(sa) }, .either => if (sa.family == familyOf(in(Target))) .{ .ipv4 = try readIpv4(sa) } else if (sa.family == familyOf(in6(Target))) .{ .ipv6 = try readIpv6(sa) } else error.UnexpectedAddressFamily, };}
/// Reads back the address of a structure of either version, dropping its port./// Which version it is, is decided as `readEndpoint` decides it.pub fn readAddress(sa: anytype) Error!Address { const Target = Pointee(@TypeOf(sa)); return switch (comptime shapeOf(Target)) { .in => .{ .ipv4 = (try readIpv4(sa)).address }, .in6 => .{ .ipv6 = (try readIpv6(sa)).address }, .either => if (sa.family == familyOf(in(Target))) .{ .ipv4 = (try readIpv4(sa)).address } else if (sa.family == familyOf(in6(Target))) .{ .ipv6 = (try readIpv6(sa)).address } else error.UnexpectedAddressFamily, };}
// The generic machinery. Everything below decides, from the type a pointer// points at, which structure is meant and where to find the `AF_INET` and// `AF_INET6` values that go with it.
/// Which of the socket address structures a type is.const Shape = enum { /// A `sockaddr_in`: an IPv4 address and nothing else. in, /// A `sockaddr_in6`: an IPv6 address and nothing else. in6, /// A `sockaddr` or a `sockaddr_storage`, either of which stands for a /// structure of any family and says which in its `family` field. either,};
fn shapeOf(comptime Target: type) Shape { // `zero` and `scope_id` tell the two apart; `addr` alone does not, and // neither does the presence of a `port`, which the packet and netlink // structures beside them also have. if (@hasField(Target, "addr") and @hasField(Target, "zero")) return .in; if (@hasField(Target, "addr") and @hasField(Target, "scope_id")) return .in6; return .either;}
/// The type of a pointer's pointee, rejecting anything that is not a pointer/// to a single socket address structure.fn Pointee(comptime Pointer: type) type { const info = @typeInfo(Pointer); if (info != .pointer or info.pointer.size != .one) @compileError( "a socket address is passed as a pointer to one, not as " ++ @typeName(Pointer), ); const Target = info.pointer.child; if (@typeInfo(Target) != .@"struct" or !@hasField(Target, "family")) @compileError( @typeName(Target) ++ " is not a socket address structure: it has no `family` field", ); return Target;}
/// The `sockaddr_in` type to read or write through a pointer to `Target`.fn in(comptime Target: type) type { return switch (shapeOf(Target)) { .in => Target, .in6 => @compileError("an IPv4 address does not fit in " ++ @typeName(Target)), // A `sockaddr` carries the nested types of its own namespace; a // `sockaddr_storage` is declared inside one and carries nothing, so // there the host's own namespace is all there is to go on. .either => if (@hasDecl(Target, "in")) Target.in else std.posix.sockaddr.in, };}
/// The `sockaddr_in6` type to read or write through a pointer to `Target`.fn in6(comptime Target: type) type { return switch (shapeOf(Target)) { .in => @compileError("an IPv6 address does not fit in " ++ @typeName(Target)), .in6 => Target, .either => if (@hasDecl(Target, "in6")) Target.in6 else std.posix.sockaddr.in6, };}
/// The address family a structure declares itself to be, taken from the/// default on its `family` field.fn familyOf(comptime Structure: type) @FieldType(Structure, "family") { const field = std.meta.fieldInfo(Structure, .family); return comptime field.attrs.defaultValue(field.type) orelse @compileError( @typeName(Structure) ++ " does not declare which address family it is", );}
/// Rejects a target that has already settled on one version, for the callers/// that do not know theirs until run time.////// The condition is forced to comptime here rather than left to the caller:/// `shapeOf` returns an ordinary value, so from a runtime context the `if`/// would be a runtime branch and the `@compileError` would fire on every/// target rather than on the wrong ones.fn requireEitherVersion(comptime Target: type) void { if (comptime shapeOf(Target) != .either) @compileError( "an address of either version needs a `sockaddr` or a `sockaddr.storage` to be written" ++ " into, not " ++ @typeName(Target) ++ "; switch on the version to write into that", );}
/// Copies a filled-in structure over whatever the pointer points at, returning/// its size.////// The bytes go through a `[*]u8` rather than a cast of the pointer itself,/// because a `*sockaddr` is only aligned as a `sockaddr` and a `sockaddr_in`/// wants more. Casting away the constness of a `*const` target is a compile/// error here, which is what keeps a read-only pointer from being written to.fn write(comptime Structure: type, value: *const Structure, sa: anytype) u32 { const bytes: [*]u8 = @ptrCast(sa); @memcpy(bytes[0..@sizeOf(Structure)], std.mem.asBytes(value)); return @sizeOf(Structure);}
/// Copies a structure out of whatever the pointer points at.fn read(comptime Structure: type, sa: anytype) Structure { const bytes: [*]const u8 = @ptrCast(sa); var value: Structure = undefined; @memcpy(std.mem.asBytes(&value), bytes[0..@sizeOf(Structure)]); return value;}
const builtin = @import("builtin");const testing = std.testing;
test writeIpv4 { var sa: std.posix.sockaddr.in = undefined; const len = writeIpv4(try .parse("192.0.2.1"), 443, &sa); try testing.expectEqual(@as(u32, @sizeOf(std.posix.sockaddr.in)), len); try testing.expect(sa.family == std.posix.AF.INET); try testing.expect((try readIpv4(&sa)).eql(try .parse("192.0.2.1:443")));}
test writeIpv6 { var sa: std.posix.sockaddr.in6 = undefined; const len = writeIpv6(try .parse("fe80::1"), 22, .{ .scope_id = 2 }, &sa); try testing.expectEqual(@as(u32, @sizeOf(std.posix.sockaddr.in6)), len); try testing.expectEqual(@as(u32, 2), sa.scope_id); try testing.expect((try readIpv6(&sa)).eql(try .parse("[fe80::1]:22")));}
test writeAddress { // The version is not known until run time, so the target has to be one // that can hold either. var storage: std.posix.sockaddr.storage = undefined; const len = writeAddress(try .parse("2001:db8::1"), 443, .{}, &storage); try testing.expectEqual(@as(u32, @sizeOf(std.posix.sockaddr.in6)), len); try testing.expect((try readAddress(&storage)).eql(try .parse("2001:db8::1")));}
test readIpv4 { var sa: std.posix.sockaddr.in = undefined; _ = writeIpv4(.loopback, 8080, &sa); try testing.expect((try readIpv4(&sa)).eql(.init(.loopback, 8080)));
// Any other family is reported rather than misread. sa.family = std.posix.AF.INET6; try testing.expectError(error.UnexpectedAddressFamily, readIpv4(&sa));}
test readIpv6 { var sa: std.posix.sockaddr.in6 = undefined; _ = writeIpv6(.loopback, 8080, .{}, &sa); // The flow label and the scope are dropped; `readIpv6Options` keeps them. try testing.expect((try readIpv6(&sa)).eql(.init(.loopback, 8080)));
sa.family = std.posix.AF.INET; try testing.expectError(error.UnexpectedAddressFamily, readIpv6(&sa));}
test readIpv6Options { var sa: std.posix.sockaddr.in6 = undefined; _ = writeIpv6(try .parse("fe80::1"), 22, .{ .scope_id = 3, .flowinfo = 7 }, &sa); try testing.expectEqual( Options{ .scope_id = 3, .flowinfo = 7 }, try readIpv6Options(&sa), );}
test readEndpoint { var storage: std.posix.sockaddr.storage = undefined; // A family-agnostic structure is read as whichever version its `family` // names. _ = writeIpv4(try .parse("192.0.2.1"), 443, &storage); try testing.expect((try readEndpoint(&storage)) == .ipv4); _ = writeIpv6(try .parse("2001:db8::1"), 443, .{}, &storage); try testing.expect((try readEndpoint(&storage)) == .ipv6);
storage.family = std.posix.AF.UNIX; try testing.expectError(error.UnexpectedAddressFamily, readEndpoint(&storage));}
test readAddress { var storage: std.posix.sockaddr.storage = undefined; _ = writeIpv6(try .parse("2001:db8::1"), 443, .{}, &storage); // The same as `readEndpoint` with the port dropped. try testing.expect((try readAddress(&storage)).eql(try .parse("2001:db8::1")));}
test "an IPv4 endpoint fills in a sockaddr_in byte for byte" { const In = std.posix.sockaddr.in; var sa: In = undefined; const e = try Ipv4Endpoint.parse("192.0.2.1:443");
try testing.expectEqual(@as(u32, @sizeOf(In)), e.writeSockaddr(&sa)); try testing.expect(sa.family == std.posix.AF.INET);
// The port and the address are both in network byte order, which is what // the bytes of the structure have to show whatever the host's order is. const bytes = std.mem.asBytes(&sa); try testing.expectEqualSlices(u8, &.{ 0x01, 0xbb }, bytes[@offsetOf(In, "port")..][0..2]); try testing.expectEqualSlices(u8, &.{ 192, 0, 2, 1 }, bytes[@offsetOf(In, "addr")..][0..4]); // Every field is written, including the padding a kernel may compare. try testing.expectEqualSlices(u8, &@as([8]u8, @splat(0)), &sa.zero);
try testing.expect(e.eql(try Ipv4Endpoint.fromSockaddr(&sa))); try testing.expect((try Ipv4Address.fromSockaddr(&sa)).eql(e.address));}
test "an IPv6 endpoint fills in a sockaddr_in6 byte for byte" { const In6 = std.posix.sockaddr.in6; var sa: In6 = undefined; const e = try Ipv6Endpoint.parse("[2001:db8::1]:443");
try testing.expectEqual(@as(u32, @sizeOf(In6)), e.writeSockaddr(&sa)); try testing.expect(sa.family == std.posix.AF.INET6);
const bytes = std.mem.asBytes(&sa); try testing.expectEqualSlices(u8, &.{ 0x01, 0xbb }, bytes[@offsetOf(In6, "port")..][0..2]); try testing.expectEqualSlices(u8, &e.address.octets, bytes[@offsetOf(In6, "addr")..][0..16]); // Left as they are for an address that carries no flow label and sits in // no particular scope. try testing.expectEqual(@as(u32, 0), sa.flowinfo); try testing.expectEqual(@as(u32, 0), sa.scope_id);
try testing.expect(e.eql(try Ipv6Endpoint.fromSockaddr(&sa))); try testing.expect((try Ipv6Address.fromSockaddr(&sa)).eql(e.address));}
test "a link-local address keeps the interface it is scoped to" { var sa: std.posix.sockaddr.in6 = undefined; const e = try Ipv6Endpoint.parse("[fe80::1]:22");
_ = e.writeSockaddrWithOptions(&sa, .{ .scope_id = 3, .flowinfo = 0xabcde }); // The scope is an interface index rather than anything that travels, so // it stays in the host's byte order; the flow label does travel. try testing.expectEqual(@as(u32, 3), sa.scope_id); try testing.expectEqual(std.mem.nativeToBig(u32, 0xabcde), sa.flowinfo);
try testing.expect(e.eql(try Ipv6Endpoint.fromSockaddr(&sa))); try testing.expectEqual( Options{ .scope_id = 3, .flowinfo = 0xabcde }, try Ipv6Endpoint.sockaddrOptions(&sa), ); try testing.expectEqual(@as(u32, 3), (try Ipv6Address.sockaddrOptions(&sa)).scope_id);}
test "a storage holds an endpoint of either version" { for ([_][]const u8{ "192.0.2.1:443", "[2001:db8::1]:443" }) |text| { var storage: std.posix.sockaddr.storage = undefined; const e = try Endpoint.parse(text);
const len = e.writeSockaddr(&storage); try testing.expectEqual(@as(u32, switch (e) { .ipv4 => @sizeOf(std.posix.sockaddr.in), .ipv6 => @sizeOf(std.posix.sockaddr.in6), }), len);
try testing.expect(e.eql(try Endpoint.fromSockaddr(&storage))); try testing.expect(e.address().eql(try Address.fromSockaddr(&storage)));
// The same bytes through the family-agnostic pointer a C call is // handed, which is what `accept` and `recvfrom` fill in. const sa: *const std.posix.sockaddr = @ptrCast(&storage); try testing.expect(e.eql(try Endpoint.fromSockaddr(sa))); }}
test "a sockaddr pointing at enough room takes either version" { // A `*sockaddr` says nothing about the size behind it, so an IPv6 address // goes through one as readily as an IPv4 one as long as the storage is // really there. var storage: std.posix.sockaddr.storage = undefined; const sa: *std.posix.sockaddr = @ptrCast(&storage);
const e = try Endpoint.parse("[2001:db8::1]:8080"); try testing.expectEqual(@as(u32, @sizeOf(std.posix.sockaddr.in6)), e.writeSockaddr(sa)); try testing.expect(e.eql(try Endpoint.fromSockaddr(&storage)));
const v4 = try Ipv4Endpoint.parse("10.0.0.1:53"); try testing.expectEqual(@as(u32, @sizeOf(std.posix.sockaddr.in)), v4.writeSockaddr(sa)); try testing.expect(v4.eql(try Ipv4Endpoint.fromSockaddr(sa)));}
test "a family that is neither is reported rather than guessed at" { var storage: std.posix.sockaddr.storage = undefined; storage.family = std.posix.AF.UNIX;
try testing.expectError(error.UnexpectedAddressFamily, Endpoint.fromSockaddr(&storage)); try testing.expectError(error.UnexpectedAddressFamily, Address.fromSockaddr(&storage)); try testing.expectError(error.UnexpectedAddressFamily, Ipv4Endpoint.fromSockaddr(&storage)); try testing.expectError(error.UnexpectedAddressFamily, Ipv6Address.fromSockaddr(&storage));
// An IPv4 structure read as IPv6, or the other way about, is the same // mistake and is caught the same way. _ = (try Ipv4Endpoint.parse("192.0.2.1:443")).writeSockaddr(&storage); try testing.expectError(error.UnexpectedAddressFamily, Ipv6Endpoint.fromSockaddr(&storage)); try testing.expect((try Endpoint.fromSockaddr(&storage)) == .ipv4);}
test "the three namespaces are one structure under three names" { // `std.posix.sockaddr`, `std.c.sockaddr` and `std.os.linux.sockaddr` all // describe the same bytes, so what one writes another reads. var sa: std.c.sockaddr.in6 = undefined; const e = try Ipv6Endpoint.parse("[2001:db8::1]:443"); _ = e.writeSockaddr(&sa); try testing.expect(e.eql(try Ipv6Endpoint.fromSockaddr(@as(*std.posix.sockaddr.in6, @ptrCast(&sa)))));
if (builtin.os.tag == .linux) { var linux_sa: std.os.linux.sockaddr.storage = undefined; _ = e.writeSockaddr(&linux_sa); // Taken from the pointer's own namespace rather than the host's, which // is the whole point: AF_INET6 is 10 here and 30 on Darwin. try testing.expectEqual(@as(u16, 10), linux_sa.family); try testing.expect(e.eql(try Ipv6Endpoint.fromSockaddr(&linux_sa))); }}
test "every address and port survives the round trip" { var prng: std.Random.DefaultPrng = .init(0x9e3779b97f4a7c15); const random = prng.random();
for (0..10_000) |_| { const port = random.int(u16); var storage: std.posix.sockaddr.storage = undefined;
const v4: Ipv4Endpoint = .init(.fromInt(random.int(u32)), port); _ = v4.writeSockaddr(&storage); try testing.expect(v4.eql(try Ipv4Endpoint.fromSockaddr(&storage)));
const v6: Ipv6Endpoint = .init(.fromInt(random.int(u128)), port); const scope_id = random.int(u32); _ = v6.writeSockaddrWithOptions(&storage, .{ .scope_id = scope_id }); try testing.expect(v6.eql(try Ipv6Endpoint.fromSockaddr(&storage))); try testing.expectEqual(scope_id, (try Ipv6Endpoint.sockaddrOptions(&storage)).scope_id); }}
test shapeOf { // `zero` and `scope_id` are what tell the two apart; `addr` alone does // not, since the packet and netlink structures beside them have one too. try testing.expectEqual(.in, shapeOf(std.posix.sockaddr.in)); try testing.expectEqual(.in6, shapeOf(std.posix.sockaddr.in6)); // Both of the family-agnostic structures stand for either version. try testing.expectEqual(.either, shapeOf(std.posix.sockaddr)); try testing.expectEqual(.either, shapeOf(std.posix.sockaddr.storage));}
test Pointee { var sa: std.posix.sockaddr.in = undefined; try testing.expect(Pointee(@TypeOf(&sa)) == std.posix.sockaddr.in); // Constness belongs to the pointer rather than to what it points at, so // a read-only pointer names the same structure. const ro: *const std.posix.sockaddr.in = &sa; try testing.expect(Pointee(@TypeOf(ro)) == std.posix.sockaddr.in);}
test in { // A structure that is already a `sockaddr_in` is itself. try testing.expect(in(std.posix.sockaddr.in) == std.posix.sockaddr.in); // A `sockaddr` carries the nested types of its own namespace. try testing.expect(in(std.posix.sockaddr) == std.posix.sockaddr.in); try testing.expect(in(std.c.sockaddr) == std.c.sockaddr.in); // A `sockaddr_storage` is declared inside a `sockaddr` and carries no // nested types of its own, so `std.posix` stands in for its namespace. try testing.expect(in(std.posix.sockaddr.storage) == std.posix.sockaddr.in);}
test in6 { try testing.expect(in6(std.posix.sockaddr.in6) == std.posix.sockaddr.in6); try testing.expect(in6(std.posix.sockaddr) == std.posix.sockaddr.in6); try testing.expect(in6(std.posix.sockaddr.storage) == std.posix.sockaddr.in6);}
test familyOf { try testing.expect(familyOf(std.posix.sockaddr.in) == std.posix.AF.INET); try testing.expect(familyOf(std.posix.sockaddr.in6) == std.posix.AF.INET6);
// Read off the structure's own declaration rather than taken from the // host, which is the whole point: AF_INET6 is 10 on Linux and 30 on // Darwin, and a constant from the wrong namespace is wrong silently. if (builtin.os.tag == .linux) { try testing.expectEqual(@as(u16, 10), familyOf(std.os.linux.sockaddr.in6)); }}
test requireEitherVersion { // Accepts the two structures that can hold either version. Anything that // has already settled on one is a compile error naming the type, which is // what stops `writeAddress` from being handed a target too small for the // version it turns out to have. requireEitherVersion(std.posix.sockaddr); requireEitherVersion(std.posix.sockaddr.storage);}
test write { // The bytes go through a `[*]u8` rather than a cast of the pointer, so a // `sockaddr_storage` takes a `sockaddr_in` whatever the two are aligned // to. var storage: std.posix.sockaddr.storage = undefined; const value: std.posix.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, 443), .addr = @bitCast([4]u8{ 192, 0, 2, 1 }), }; const len = write(std.posix.sockaddr.in, &value, &storage); try testing.expectEqual(@as(u32, @sizeOf(std.posix.sockaddr.in)), len); try testing.expect((try readIpv4(&storage)).eql(try .parse("192.0.2.1:443")));}
test read { var sa: std.posix.sockaddr.in6 = undefined; const address = try Ipv6Address.parse("2001:db8::1"); _ = writeIpv6(address, 443, .{}, &sa);
const value = read(std.posix.sockaddr.in6, &sa); try testing.expectEqualSlices(u8, &address.octets, &value.addr); // Copied out as the structure holds it, so the port is still in network // byte order. try testing.expectEqual(std.mem.nativeToBig(u16, 443), value.port);}