@@ -9,7 +9,7 @@ use bytes::Bytes;
99use http:: { uri:: Uri , HeaderValue } ;
1010use hyper:: rt;
1111use 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 } ;
1313use 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
4243impl 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