From acf9bbe0fdfdf4994fa4e1e067f7da6c186bd8e0 Mon Sep 17 00:00:00 2001 From: Mihai Chiorean Date: Fri, 6 Mar 2026 00:49:57 -0800 Subject: [PATCH] Support scoped IPv6 addresses in SocketAddress.init(ipAddress:port:) (#3525) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Motivation `SocketAddress.init(ipAddress:port:)` uses `inet_pton` to parse IP address strings. `inet_pton` does not support the `%scope` suffix used in IPv6 link-local addresses (e.g., `fe80::1%eth0`), causing these addresses to fail with `failedToParseIPString`. This forces downstream consumers like grpc-swift-nio-transport to reimplement scoped IPv6 parsing using `getaddrinfo` themselves. Related: https://github.com/grpc/grpc-swift-nio-transport/issues/147 ### Modifications When the IP address string contains a `%` character, fall back to `getaddrinfo` with `AI_NUMERICHOST` instead of `inet_pton`. This properly parses the `%scope` suffix and sets `sin6_scope_id` in the resulting `sockaddr_in6`. The scoped path is extracted into a private `_parseScopedIPv6` helper, guarded with `#if !os(Windows) && !os(WASI)`. The non-scoped `inet_pton` path is completely unchanged. Added 5 tests: - Named scope (`fe80::1%lo`) — verifies `sin6_scope_id` matches `if_nametoindex` - Numeric scope (`fe80::1%1`) — verifies numeric index parsing - Scoped vs non-scoped inequality — different `sin6_scope_id` means different addresses - Invalid scopes rejected — empty scope and nonexistent interface both throw - Non-scoped regression — `::1` still works with `scope_id == 0` ### Result `SocketAddress(ipAddress: "fe80::1%eth0", port: 80)` now succeeds and preserves the scope ID in `sin6_scope_id`. Non-scoped addresses continue to work exactly as before. ### Context This came up while working on IPv6 link-local support in [grpc-swift-nio-transport#146](https://github.com/grpc/grpc-swift-nio-transport/pull/146), where the workaround was to use `getaddrinfo` directly in the gRPC layer. The reviewer suggested upstreaming this to swift-nio so the workaround can be removed. --------- Co-authored-by: Cory Benfield --- Sources/NIOCore/SocketAddresses.swift | 50 +++++++++ Tests/NIOPosixTests/SocketAddressTest.swift | 107 ++++++++++++++++++++ 2 files changed, 157 insertions(+) diff --git a/Sources/NIOCore/SocketAddresses.swift b/Sources/NIOCore/SocketAddresses.swift index 30bf3853e..18f6740f3 100644 --- a/Sources/NIOCore/SocketAddresses.swift +++ b/Sources/NIOCore/SocketAddresses.swift @@ -345,6 +345,10 @@ public enum SocketAddress: CustomStringConvertible, Sendable { /// Create a new `SocketAddress` for an IP address in string form. /// + /// Supports both IPv4 and IPv6 addresses. IPv6 addresses may include a scope ID + /// suffix (e.g., `"fe80::1%eth0"`) for link-local addresses; the scope ID will be + /// preserved in the resulting `sockaddr_in6.sin6_scope_id`. + /// /// - Parameters: /// - ipAddress: The IP address, in string form. /// - port: The target port. @@ -366,6 +370,17 @@ public enum SocketAddress: CustomStringConvertible, Sendable { // IPv6 address. } + // IPv6 addresses with scope IDs (e.g. "fe80::1%eth0") are not supported by + // inet_pton. Use getaddrinfo with AI_NUMERICHOST which handles %scope and + // properly sets sin6_scope_id. + if ipAddress.utf8.contains(UInt8(ascii: "%")) { + #if !os(Windows) && !os(WASI) + return try Self._parseScopedIPv6(ipAddress, port: port) + #else + throw SocketAddressError.failedToParseIPString(ipAddress) + #endif + } + do { var ipv6Addr = in6_addr() try NIOBSDSocket.inet_pton(addressFamily: .inet6, addressDescription: $0, address: &ipv6Addr) @@ -386,6 +401,41 @@ public enum SocketAddress: CustomStringConvertible, Sendable { } } + #if !os(Windows) && !os(WASI) + /// Parse a scoped IPv6 address (containing `%scope`) using `getaddrinfo` with `AI_NUMERICHOST`. + private static func _parseScopedIPv6(_ ipAddress: String, port: Int) throws -> SocketAddress { + // Reject empty scope (e.g. "fe80::1%") before calling getaddrinfo, because + // some platforms (macOS) silently accept it with scope_id == 0. + guard let percentIndex = ipAddress.firstIndex(of: "%"), + ipAddress[ipAddress.index(after: percentIndex)...].isEmpty == false + else { + throw SocketAddressError.failedToParseIPString(ipAddress) + } + + var hints = addrinfo() + hints.ai_family = AF_INET6 + hints.ai_flags = AI_NUMERICHOST + var result: UnsafeMutablePointer? + let status = getaddrinfo(ipAddress, String(port), &hints, &result) + defer { if result != nil { freeaddrinfo(result) } } + guard status == 0, let addrInfo = result, let ai_addr = addrInfo.pointee.ai_addr, + ai_addr.pointee.sa_family == sa_family_t(AF_INET6) + else { + throw SocketAddressError.failedToParseIPString(ipAddress) + } + let sockaddr = ai_addr.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { $0.pointee } + + // On macOS, getaddrinfo can succeed even for nonexistent interface names, + // silently returning scope_id == 0. A valid scoped address must have a + // nonzero scope_id. + guard sockaddr.sin6_scope_id != 0 else { + throw SocketAddressError.failedToParseIPString(ipAddress) + } + + return .v6(.init(address: sockaddr, host: ipAddress)) + } + #endif + /// Create a new `SocketAddress` for an IP address in ByteBuffer form. /// /// - Parameters: diff --git a/Tests/NIOPosixTests/SocketAddressTest.swift b/Tests/NIOPosixTests/SocketAddressTest.swift index e08ebbe74..36336a1dd 100644 --- a/Tests/NIOPosixTests/SocketAddressTest.swift +++ b/Tests/NIOPosixTests/SocketAddressTest.swift @@ -157,6 +157,113 @@ class SocketAddressTest: XCTestCase { } } + func testCanCreateScopedIPv6AddressFromString() throws { + #if os(Windows) || os(WASI) + // Scoped IPv6 parsing uses getaddrinfo, not available on these platforms. + #else + let loopback: String + #if canImport(Darwin) + loopback = "lo0" + #else + loopback = "lo" + #endif + + let expectedIndex = if_nametoindex(loopback) + guard expectedIndex != 0 else { return } + + let sa = try SocketAddress(ipAddress: "fe80::1%\(loopback)", port: 443) + if case .v6(let address) = sa { + XCTAssertEqual(address.address.sin6_family, sa_family_t(NIOBSDSocket.AddressFamily.inet6.rawValue)) + XCTAssertEqual(address.address.sin6_port, in_port_t(443).bigEndian) + XCTAssertEqual(address.address.sin6_flowinfo, 0) + XCTAssertEqual(address.address.sin6_scope_id, expectedIndex) + XCTAssertEqual(address.host, "fe80::1%\(loopback)") + } else { + XCTFail("Invalid address: \(sa)") + } + #endif + } + + func testCanCreateScopedIPv6WithNumericIndex() throws { + #if os(Windows) || os(WASI) + // Scoped IPv6 parsing uses getaddrinfo, not available on these platforms. + #else + // Use the loopback interface index so the test isn't fragile on systems + // where index 1 might not exist. + let loopback: String + #if canImport(Darwin) + loopback = "lo0" + #else + loopback = "lo" + #endif + let expectedIndex = if_nametoindex(loopback) + guard expectedIndex != 0 else { return } + + // getaddrinfo accepts both interface names (%lo) and numeric indices (%1). + let sa = try SocketAddress(ipAddress: "fe80::1%\(expectedIndex)", port: 80) + if case .v6(let address) = sa { + XCTAssertEqual(address.address.sin6_flowinfo, 0) + XCTAssertEqual(address.address.sin6_scope_id, expectedIndex) + XCTAssertEqual(address.address.sin6_port, in_port_t(80).bigEndian) + } else { + XCTFail("Invalid address: \(sa)") + } + #endif + } + + func testScopedAndNonScopedIPv6AreNotEqual() throws { + #if os(Windows) || os(WASI) + #else + let loopback: String + #if canImport(Darwin) + loopback = "lo0" + #else + loopback = "lo" + #endif + guard if_nametoindex(loopback) != 0 else { return } + + let scoped = try SocketAddress(ipAddress: "fe80::1%\(loopback)", port: 80) + let nonScoped = try SocketAddress(ipAddress: "fe80::1", port: 80) + // sin6_scope_id differs, so these should not be equal. + XCTAssertNotEqual(scoped, nonScoped) + #endif + } + + func testRejectsInvalidScopedIPv6() { + #if os(Windows) || os(WASI) + #else + // Empty scope after % + XCTAssertThrowsError(try SocketAddress(ipAddress: "fe80::1%", port: 80)) { error in + switch error as? SocketAddressError { + case .some(.failedToParseIPString("fe80::1%")): + () // ok + default: + XCTFail("unexpected error: \(error)") + } + } + // Nonexistent interface name + XCTAssertThrowsError(try SocketAddress(ipAddress: "fe80::1%doesnotexist999", port: 80)) { error in + switch error as? SocketAddressError { + case .some(.failedToParseIPString("fe80::1%doesnotexist999")): + () // ok + default: + XCTFail("unexpected error: \(error)") + } + } + #endif + } + + func testCanCreateNonScopedIPv6AfterScopedIPv6Support() throws { + // Regression: ensure non-scoped IPv6 still works after adding scoped support. + let sa = try SocketAddress(ipAddress: "::1", port: 80) + if case .v6(let address) = sa { + XCTAssertEqual(address.address.sin6_scope_id, 0) + XCTAssertEqual(address.address.sin6_port, in_port_t(80).bigEndian) + } else { + XCTFail("Invalid address: \(sa)") + } + } + func testRejectsNonIPStrings() { XCTAssertThrowsError(try SocketAddress(ipAddress: "definitelynotanip", port: 800)) { error in switch error as? SocketAddressError {