Is there a way to get Hyper to instruct the network interface to assign a specific source port to all outgoing HTTP requests?
You can tell hyper how to open the connection by defining a custom Connector
like this:
use std::task::{self, Poll};
use hyper::{service::Service, Uri};
use tokio::net::TcpStream;
use futures::future::BoxFuture;
#[derive(Clone)]
struct MyConnector {
port: u32,
}
impl Service<Uri> for MyConnector {
type Response = TcpStream;
type Error = std::io::Error;
type Future = BoxFuture<'static, Result<TcpStream, Self::Error>>;
fn poll_ready(&mut self, _: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, uri: Uri) -> Self::Future {
Box::pin(async move {
// ... create your TcpStream here
})
}
}
This will allow you to set whatever options you want on the TcpStream
. Please see my other answer that explains how to call bind
on the connection yourself, which is necessary to set the source port.
Now that you have defined the connector, you can use it when creating a new hyper Client
, and any connections opened on that Client
will use the specified connector.
let client = hyper::Client::builder()
.build::<_, hyper::Body>(MyConnector { port: 1234 });
// now open your connection using `client`