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

时间:2020-07-10 16:00:17

标签: rust hyper

是否可以让Hyper指示网络接口为所有传出的HTTP请求分配特定的源端口?

1 个答案:

答案 0 :(得分:2)

您可以通过定义以下自定义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,这是设置源端口所必需的。

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

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

// now open your connection using `client`
相关问题