Skip to content

Commit 65def4e

Browse files
committed
Adds local_address as an option Endpoint builder.
1 parent 5ad89bf commit 65def4e

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

tonic/src/transport/channel/endpoint.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use bytes::Bytes;
99
use http::{uri::Uri, HeaderValue};
1010
use hyper::rt;
1111
use hyper_util::client::legacy::connect::HttpConnector;
12-
use std::{fmt, future::Future, pin::Pin, str::FromStr, time::Duration};
12+
use std::{fmt, future::Future, net::IpAddr, pin::Pin, str::FromStr, time::Duration};
1313
use tower_service::Service;
1414

1515
/// Channel builder.
@@ -37,6 +37,7 @@ pub struct Endpoint {
3737
pub(crate) connect_timeout: Option<Duration>,
3838
pub(crate) http2_adaptive_window: Option<bool>,
3939
pub(crate) executor: SharedExec,
40+
pub(crate) local_address: Option<IpAddr>,
4041
}
4142

4243
impl Endpoint {
@@ -325,12 +326,30 @@ impl Endpoint {
325326
)
326327
}
327328

329+
/// Set the local address
330+
///
331+
/// This sets the IP address the client will use. By default we let hyper select the IP address.
332+
/// ```
333+
/// # use std::net::IpAddr;
334+
/// # use std::str::FromStr;
335+
/// # use tonic::transport::Endpoint;
336+
/// # let mut builder = Endpoint::from_static("https://example.com");
337+
/// # builder.local_address(IpAddr::from_str("127.0.0.1").expect("Unable to parse IP address"));
338+
/// ```
339+
pub fn local_address(self, addr: IpAddr) -> Self {
340+
Endpoint {
341+
local_address: Some(addr),
342+
..self
343+
}
344+
}
345+
328346
pub(crate) fn http_connector(&self) -> service::Connector<HttpConnector> {
329347
let mut http = HttpConnector::new();
330348
http.enforce_http(false);
331349
http.set_nodelay(self.tcp_nodelay);
332350
http.set_keepalive(self.tcp_keepalive);
333351
http.set_connect_timeout(self.connect_timeout);
352+
http.set_local_address(self.local_address);
334353
self.connector(http)
335354
}
336355

@@ -452,6 +471,7 @@ impl From<Uri> for Endpoint {
452471
connect_timeout: None,
453472
http2_adaptive_window: None,
454473
executor: SharedExec::tokio(),
474+
local_address: None,
455475
}
456476
}
457477
}

0 commit comments

Comments
 (0)