diff --git a/Sources/NIOCore/BSDSocketAPI.swift b/Sources/NIOCore/BSDSocketAPI.swift index 60b6ae51a..e655e7a81 100644 --- a/Sources/NIOCore/BSDSocketAPI.swift +++ b/Sources/NIOCore/BSDSocketAPI.swift @@ -567,6 +567,18 @@ extension NIOBSDSocket.Option { public static var so_timestamp: NIOBSDSocket.Option { NIOBSDSocket.Option(rawValue: SO_TIMESTAMP) } + + /// Allows multiple sockets to be bound to an identical address and port. + /// + /// - Important: The behavior of this socket option is platform-specific. See platform documentation for details. + /// + /// - Seealso: `man 2 socket` (Linux) + /// - Seealso: `man 2 setsockopt` (Darwin) + /// - Seealso: https://stackoverflow.com/questions/14388706/how-do-so-reuseaddr-and-so-reuseport-differ + @inlinable + public static var so_reuseport: NIOBSDSocket.Option { + NIOBSDSocket.Option(rawValue: SO_REUSEPORT) + } } #endif diff --git a/Tests/NIOPosixTests/DatagramChannelTests.swift b/Tests/NIOPosixTests/DatagramChannelTests.swift index d37a2ceb4..8b51627eb 100644 --- a/Tests/NIOPosixTests/DatagramChannelTests.swift +++ b/Tests/NIOPosixTests/DatagramChannelTests.swift @@ -634,6 +634,33 @@ class DatagramChannelTests: XCTestCase { #endif } + func testSettingSoReuseportAllowsTwoChannelsToBindTheSamePort() throws { + #if os(Windows) + throw XCTSkip("SO_REUSEPORT is not available on Windows") + #else + let first = try assertNoThrowWithValue( + DatagramBootstrap(group: group) + .channelOption(.socketOption(.so_reuseport), value: 1) + .bind(host: "127.0.0.1", port: 0) + .wait() + ) + defer { + XCTAssertNoThrow(try first.close().wait()) + } + let second = try assertNoThrowWithValue( + DatagramBootstrap(group: group) + .channelOption(.socketOption(.so_reuseport), value: 1) + .bind(to: first.localAddress!) + .wait() + ) + defer { + XCTAssertNoThrow(try second.close().wait()) + } + XCTAssertTrue(try getBoolSocketOption(channel: first, level: .socket, name: .so_reuseport)) + XCTAssertTrue(try getBoolSocketOption(channel: second, level: .socket, name: .so_reuseport)) + #endif + } + func testUnprocessedOutboundUserEventFailsOnDatagramChannel() throws { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer {