@@ -433,11 +433,7 @@ where
433
433
. map_err ( ConnectError :: dns) ?;
434
434
let addrs = addrs
435
435
. map ( |mut addr| {
436
- // Respect explicit ports in the URI,
437
- // and non `0` ports resolved from a custom dns resolver.
438
- if dst. port ( ) . is_some ( ) || addr. port ( ) == 0 {
439
- addr. set_port ( port)
440
- } ;
436
+ set_port ( & mut addr, port, dst. port ( ) . is_some ( ) ) ;
441
437
442
438
addr
443
439
} )
@@ -830,9 +826,19 @@ impl ConnectingTcp<'_> {
830
826
}
831
827
}
832
828
829
+ /// Respect explicit ports in the URI, if none, either
830
+ /// keep non `0` ports resolved from a custom dns resolver,
831
+ /// or use the default port for the scheme.
832
+ fn set_port ( addr : & mut SocketAddr , host_port : u16 , explicit : bool ) {
833
+ if explicit || addr. port ( ) == 0 {
834
+ addr. set_port ( host_port)
835
+ } ;
836
+ }
837
+
833
838
#[ cfg( test) ]
834
839
mod tests {
835
840
use std:: io;
841
+ use std:: net:: SocketAddr ;
836
842
837
843
use :: http:: Uri ;
838
844
@@ -841,6 +847,8 @@ mod tests {
841
847
use super :: super :: sealed:: { Connect , ConnectSvc } ;
842
848
use super :: { Config , ConnectError , HttpConnector } ;
843
849
850
+ use super :: set_port;
851
+
844
852
async fn connect < C > (
845
853
connector : C ,
846
854
dst : Uri ,
@@ -1239,4 +1247,22 @@ mod tests {
1239
1247
panic ! ( "test failed" ) ;
1240
1248
}
1241
1249
}
1250
+
1251
+ #[ test]
1252
+ fn test_set_port ( ) {
1253
+ // Respect explicit ports no matter what the resolved port is.
1254
+ let mut addr = SocketAddr :: from ( ( [ 0 , 0 , 0 , 0 ] , 6881 ) ) ;
1255
+ set_port ( & mut addr, 42 , true ) ;
1256
+ assert_eq ! ( addr. port( ) , 42 ) ;
1257
+
1258
+ // Ignore default host port, and use the socket port instead.
1259
+ let mut addr = SocketAddr :: from ( ( [ 0 , 0 , 0 , 0 ] , 6881 ) ) ;
1260
+ set_port ( & mut addr, 443 , false ) ;
1261
+ assert_eq ! ( addr. port( ) , 6881 ) ;
1262
+
1263
+ // Use the default port if the resolved port is `0`.
1264
+ let mut addr = SocketAddr :: from ( ( [ 0 , 0 , 0 , 0 ] , 0 ) ) ;
1265
+ set_port ( & mut addr, 443 , false ) ;
1266
+ assert_eq ! ( addr. port( ) , 443 ) ;
1267
+ }
1242
1268
}
0 commit comments