Skip to content

Use std.posix.sockaddr types for IP addresses - #110

Merged
lalinsky merged 3 commits into
mainfrom
backport-posix-sockaddr
Nov 1, 2025
Merged

lalinsky merged 3 commits into
mainfrom
backport-posix-sockaddr

Conversation

@lalinsky

@lalinsky lalinsky commented Nov 1, 2025

Copy link
Copy Markdown
Owner

Backport changes from zig-0.16 branch to use std.posix.sockaddr.in and std.posix.sockaddr.in6 directly instead of std.net.Ip4Address and std.net.Ip6Address.

This reduces dependency on std.net types and provides a foundation for removing std.net dependency entirely in Zig 0.15.

Changes:

  • Add getSockAddrLen() helper function
  • Update IpAddress union to use std.posix.sockaddr types
  • Implement custom initIp4/initIp6 functions
  • Implement pure Zig IPv4/IPv6 parsers (cross-platform)
  • Custom format() for IPv4, IPv6 with :: compression support
  • Update all socket operations (bind, connect, sendTo, accept)
  • Add format validation to tests to catch byte-order bugs

Backport changes from zig-0.16 branch to use std.posix.sockaddr.in and
std.posix.sockaddr.in6 directly instead of std.net.Ip4Address and
std.net.Ip6Address.

This reduces dependency on std.net types and provides a foundation for
removing std.net dependency entirely in Zig 0.15.

Changes:
- Add getSockAddrLen() helper function
- Update IpAddress union to use std.posix.sockaddr types
- Implement custom initIp4/initIp6 functions
- Implement pure Zig IPv4/IPv6 parsers (cross-platform)
- Custom format() for IPv4, IPv6 with :: compression support
- Update all socket operations (bind, connect, sendTo, accept)
- Add format validation to tests to catch byte-order bugs
@coderabbitai

coderabbitai Bot commented Nov 1, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

Replaced higher-level IP/Address types with POSIX sockaddr-based storage, added getSockAddrLen and addressToStorage helpers, implemented raw IPv4/IPv6 parsing/formatting and conditional Unix-socket handling, and updated connect/bind/send/receive flows and vendor backends to use sockaddr.storage.

Changes

Cohort / File(s) Summary
Core networking
src/io/net.zig
IpAddress now stores std.posix.sockaddr.in / sockaddr.in6; added initIp4/initIp6/unspecified, parseIp4/parseIp6/parseIp/parseIpAndPort, updated getPort/setPort, IPv6 compression formatting, has_unix_sockets conditional UnixAddress, added getSockAddrLen usage and memcpy-based address handling; netConnect/netListen/netBind now use Address.
Network tests
src/io/test/net.zig
Added runtime checks that IpAddress formatting matches expected IPv4/IPv6 strings and that parseIpAndPort formatting is correct.
POSIX utilities
vendor/libxev/src/posix.zig
Added getSockAddrLen(addr: *const posix.sockaddr) posix.socklen_t and addressToStorage(addr: std.net.Address) posix.sockaddr.storage helpers for computing sockaddr lengths and converting Addresses to fixed storage.
Event loop backends
vendor/libxev/src/backend/{epoll.zig,io_uring.zig,iocp.zig,kqueue.zig}, vendor/libxev/src/watcher/tcp.zig
Switched Operation.connect.addr (and related fields) from std.net.Address to posix.sockaddr.storage; syscall submissions now pass @ptrCast(&addr) and use getSockAddrLen(...); tests updated to use addressToStorage(address) when constructing connect ops.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Pay special attention to:
    • Correctness of getSockAddrLen across AF_INET, AF_INET6, AF_UNIX and default storage.
    • All memcpy/pointer casts to ensure correct byte counts for bind/connect/sendto/recv.
    • IPv6 formatting/compression and IPv4-mapped IPv6 edge cases.
    • Backend Operation.connect.addr signature changes (ABI/union layout in vendor code).
    • Conditional has_unix_sockets impacts on UnixAddress layout and conversions.

Possibly related PRs

Poem

Raw sockaddrs step into place, bytes counted, not a trace.
Dots and colons learn to sing, zero-runs fold in on a wing.
memcpy hums, backends swap the key — networking trimmed to what it needs to be.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Use std.posix.sockaddr types for IP addresses" directly describes the core refactoring objective shown in the changeset. The raw summary confirms the main changes involve replacing std.net.Ip4Address and std.net.Ip6Address with std.posix.sockaddr.in and std.posix.sockaddr.in6 throughout the codebase, including updates to IpAddress union definitions, socket operations, and backend implementations. The title is concise, specific, and avoids vague terminology or noise, making it clear to anyone reviewing history that this PR is about switching the internal address representation to raw POSIX sockaddr types.
Description Check ✅ Passed The description is well-aligned with the actual changeset and provides meaningful detail about the refactoring. It explains the motivation (reducing std.net dependency), identifies the core change (switching to std.posix.sockaddr types), and lists specific implementations added (getSockAddrLen helper, custom IPv4/IPv6 parsers, format functions with compression support, socket operation updates). This directly corresponds to the modifications shown in the raw summary across src/io/net.zig, vendor/libxev modules, and test files, making the description substantive rather than vague or generic.

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3275e21 and aac0745.

📒 Files selected for processing (2)
  • vendor/libxev/src/backend/iocp.zig (4 hunks)
  • vendor/libxev/src/backend/kqueue.zig (3 hunks)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/io/net.zig (2)

142-160: Minor redundancy in parseIpAndPort.

Lines 144-145 call indexOf for "[" twice. The second call is redundant since you're already inside the block where it returned non-null. Consider simplifying:

-    if (std.mem.indexOf(u8, name, "[")) |_| {
-        const start = std.mem.indexOf(u8, name, "[") orelse return error.InvalidFormat;
+    if (std.mem.indexOf(u8, name, "[")) |start| {
         const end = std.mem.indexOf(u8, name, "]") orelse return error.InvalidFormat;

804-853: Inconsistent use of has_unix_sockets constant.

Line 13 defines has_unix_sockets = std.net.has_unix_sockets, and line 829 uses it. However, lines 804 and 853 still reference std.net.has_unix_sockets directly. For consistency, use the local constant:

-    if (!std.net.has_unix_sockets) unreachable;
+    if (!has_unix_sockets) unreachable;
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aadfddb and 715ebb3.

📒 Files selected for processing (2)
  • src/io/net.zig (11 hunks)
  • src/io/test/net.zig (2 hunks)
🔇 Additional comments (12)
src/io/test/net.zig (3)

27-30: Good test coverage for byte-order validation.

The format validation correctly verifies the round-trip behavior (parse → format → string comparison), which will catch byte-order issues in the port and address conversions. Buffer size of 32 bytes is adequate for IPv4 addresses with ports.


37-40: IPv6 format validation looks good.

Testing the formatted output catches potential issues with byte ordering and ensures the IPv6 compression logic produces correct results. Buffer size of 64 bytes is appropriate for IPv6 addresses with brackets and port notation.


58-68: Comprehensive parseIpAndPort validation.

Testing both IPv4 and IPv6 address:port formats ensures the parsing logic correctly handles both cases. The format checks validate that the output matches the expected canonical form, catching any byte-order or formatting bugs.

src/io/net.zig (9)

33-39: initIp4 correctly handles byte order and alignment.

The port conversion to big-endian (line 36) is correct for network byte order. The alignment handling at line 37 properly deals with the [4]u8 → u32 conversion using align(1) to indicate the pointer may be unaligned.


63-73: parseIp4 implementation looks solid.

Edge cases are properly handled:

  • Bounds checking prevents buffer overflow (line 68)
  • parseInt catches non-numeric input and values > 255 (line 69)
  • Final validation ensures exactly 4 octets (line 71)

75-132: IPv6 parser is complex but correct.

The implementation properly handles IPv6 abbreviations using a two-buffer approach. Key validations:

  • Prevents multiple :: abbreviations (line 88)
  • Overflow checks for hex values (lines 105-110)
  • Bounds checking throughout
  • Correct reassembly of abbreviated addresses (line 127)

The complexity is inherent to IPv6 parsing, and the logic appears sound.


182-263: IPv6 formatting with compression is well-implemented.

The formatter correctly:

  • Detects and formats IPv4-mapped IPv6 addresses (lines 192-202)
  • Finds the longest run of zeros for :: compression (lines 211-230)
  • Only compresses runs of 2+ zeros per RFC 5952 (line 232)
  • Properly emits the compressed notation (lines 238-259)

The logic for skipping the compressed range (line 248) works correctly with the loop increment.


164-180: Port byte-order conversions are correct.

getPort and setPort properly convert between native and network byte order (big-endian) for both IPv4 and IPv6. This matches the initialization in initIp4 (line 36) and initIp6 (line 56).


285-308: Conditional Unix socket support is consistently guarded.

The un field having type void when has_unix_sockets is false is an unconventional pattern. All access points are properly guarded with if (!has_unix_sockets) unreachable; checks (lines 290, 303), which prevents accessing the void field at runtime. This works but is somewhat fragile compared to compile-time guarantees.


552-567: Socket sendTo operations correctly use address lengths.

The memcpy approach at line 564 properly copies only the required bytes for the address family (determined by getSockAddrLen). This avoids including padding or uninitialized data.


983-995: netConnect properly updated for new Address type.

The signature change from std.net.Address to Address is consistent with the refactor goals. The memcpy at line 992 correctly copies only the required address bytes using getSockAddrLen.


17-26: Build verification confirms the code compiles cleanly on WASI. The std.posix.sockaddr.un reference doesn't cause compilation issues, so the current implementation is fine as-is. The platform guards already prevent AF.UNIX addresses from being created when unsupported, making the unreachable branch theoretically safe even without explicit conditionals.

The suggested refactor was optional; the code works.

Update libxev to use posix.sockaddr.storage instead of std.net.Address
for TCP connect operations across all backends (io_uring, epoll, kqueue,
iocp). This reduces dependency on std.net types and aligns with the
approach used in Zig 0.16.

Changes:
- Add getSockAddrLen() and addressToStorage() helpers in posix.zig
- Update connect operation struct in all backends
- Convert std.net.Address to sockaddr.storage in tcp.zig
Update remaining test cases that were using std.net.Address directly
for connect operations to use addressToStorage() helper.
@lalinsky
lalinsky merged commit 375e59d into main Nov 1, 2025
@lalinsky
lalinsky deleted the backport-posix-sockaddr branch November 1, 2025 07:35

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
vendor/libxev/src/backend/io_uring.zig (1)

434-438: Consider extracting the repeated cast.

The @ptrCast(&v.addr) appears twice in the connect preparation. You could store it in a local variable to reduce duplication:

-.connect => |*v| sqe.prep_connect(
-    v.socket,
-    @ptrCast(&v.addr),
-    posix_utils.getSockAddrLen(@ptrCast(&v.addr)),
-),
+.connect => |*v| {
+    const addr_ptr = @ptrCast(&v.addr);
+    sqe.prep_connect(
+        v.socket,
+        addr_ptr,
+        posix_utils.getSockAddrLen(addr_ptr),
+    );
+},
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 715ebb3 and 3275e21.

📒 Files selected for processing (6)
  • vendor/libxev/src/backend/epoll.zig (3 hunks)
  • vendor/libxev/src/backend/io_uring.zig (4 hunks)
  • vendor/libxev/src/backend/iocp.zig (3 hunks)
  • vendor/libxev/src/backend/kqueue.zig (2 hunks)
  • vendor/libxev/src/posix.zig (1 hunks)
  • vendor/libxev/src/watcher/tcp.zig (2 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-10-21T10:00:56.962Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 62
File: src/utils/queue.zig:141-147
Timestamp: 2025-10-21T10:00:56.962Z
Learning: In work-stealing queues implemented in src/utils/queue.zig, stealers only modify the victim's head position, never the tail. The tail is exclusively owned by the owner thread, so no atomic acquire operations are needed when the owner reads its own tail.

Applied to files:

  • vendor/libxev/src/backend/iocp.zig
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.

Applied to files:

  • vendor/libxev/src/backend/io_uring.zig
🪛 GitHub Actions: CI
vendor/libxev/src/backend/kqueue.zig

[error] 2443-2443: Command failed: cd vendor/libxev && zig build test | Type mismatch: expected type 'c.sockaddr__struct_2232.storage', found 'net.Address' at .addr assignment (src/backend/kqueue.zig:2443).

🔇 Additional comments (3)
vendor/libxev/src/backend/io_uring.zig (3)

6-6: Import added for POSIX address utilities.

Clean addition. The posix_utils module provides the address conversion and length calculation functions needed for the sockaddr migration.


1015-1018: Type migration from std.net.Address to posix.sockaddr.storage.

This change removes the high-level abstraction in favor of direct POSIX types. Note that unlike the accept operation which initializes addr = undefined, the connect operation correctly requires the caller to provide a valid address, since connect needs a destination.


1584-1604: Address conversion in test works correctly.

The addressToStorage helper cleanly converts the std.net.Address to the new posix.sockaddr.storage format. The test successfully establishes a connection (verified at line 1609), confirming the conversion preserves the address information correctly.

Comment thread vendor/libxev/src/backend/iocp.zig Resolved
Comment thread vendor/libxev/src/backend/kqueue.zig Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant