1

Is there a way to get Hyper to instruct the network interface to assign a specific source port to all outgoing HTTP requests?

adv
  • 357
  • 5
  • 18
  • Can you clarify why you want this? Different requests are different connections and would therefore require different ports if multiple are needed at the same time. The source port usually isn't relevant. – kmdreko Jul 10 '20 at 17:14
  • I am trying to find a way to bind the source port locally within the application without having to resort to the blugeon of changing `/proc/sys/net/ipv4/ip_local_port_range` assuming my Ubuntu Docker will even allow it... The problem is that we are trying to filter with iptables on application and that requires some unique marker to flag off of. – adv Jul 10 '20 at 19:59

1 Answers1

1

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`
Alice Ryhl
  • 3,574
  • 1
  • 18
  • 37