Skip to content

Add local port binding to HTTPClient.Configuration - #914

Open
VictorDebray wants to merge 2 commits into
swift-server:mainfrom
VictorDebray:feat/add-local-port-binding
Open

Add local port binding to HTTPClient.Configuration#914
VictorDebray wants to merge 2 commits into
swift-server:mainfrom
VictorDebray:feat/add-local-port-binding

Conversation

@VictorDebray

Copy link
Copy Markdown

Adds a localPort: Int knob on HTTPClient.Configuration that pins the TCP source port the connection binds to before connecting, plus a per-request HTTPClientRequest.localPort override. 0 (the default) keeps the previous behaviour of letting the OS assign an ephemeral port.

localPort is threaded through RequestOptions and ConnectionPool.Key alongside the existing localAddress, so connections with different (localAddress, localPort) pairs are pooled separately. Both the NIOTS (requiredLocalEndpoint) and NIOPosix (bind(to:)) bootstraps in the plain and TLS paths honour it.

Adds a `localPort: Int` knob on `HTTPClient.Configuration` that pins the TCP
source port the connection binds to before connecting, plus a per-request
`HTTPClientRequest.localPort` override. `0` (the default) keeps the previous
behaviour of letting the OS assign an ephemeral port.

`localPort` is threaded through `RequestOptions` and `ConnectionPool.Key`
alongside the existing `localAddress`, so connections with different
`(localAddress, localPort)` pairs are pooled separately. Both the NIOTS
(`requiredLocalEndpoint`) and NIOPosix (`bind(to:)`) bootstraps in the plain
and TLS paths honour it.

@fabianfett fabianfett left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks like a solid PR. Thank you. However before merging, we will need tests, that validate that the outgoing request has actually been made from the specified port. We will need this for the old (EventLoopFuture) API as well as the new one. Overwriting the settings also needs to be tested.

@fabianfett fabianfett added kind/feature New feature. 🆕 semver/minor Adds new public API. labels Aug 6, 2026
Reject localPort values outside 0...65535 with a new invalidLocalPort error instead of failing silently or misbehaving at bind time.
@VictorDebray

Copy link
Copy Markdown
Author

I have added the needed tests. Thanks for the review!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/feature New feature. 🆕 semver/minor Adds new public API.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants