如何让 Rust Hyper 指定传出源端口?

How to get Rust Hyper to specify outgoing source port?

有没有办法让 Hyper 指示网络接口为所有传出的 HTTP 请求分配一个特定的源端口?

您可以通过定义自定义 Connector 来告诉 hyper 如何打开连接:

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
        })
    }
}

这将允许您在 TcpStream 上设置任何您想要的选项。请参阅 my other answer,其中解释了如何自己在连接上调用 bind,这是设置源端口所必需的。

现在您已经定义了连接器,您可以在创建新的 hyper Client 时使用它,并且在那个 Client 上打开的任何连接都将使用指定的连接器。

let client = hyper::Client::builder()
    .build::<_, hyper::Body>(MyConnector { port: 1234 });

// now open your connection using `client`