【问题标题】:How to use IF_INET6 - IPV6 when sending a HTTP request in Rust在 Rust 中发送 HTTP 请求时如何使用 IF_INET6 - IPV6
【发布时间】:2021-05-20 21:19:59
【问题描述】:

我正在尝试使用 IPv6 发送 HTTP 请求。

虽然有很多 HTTP 库(reqwesthyper 等)。我找不到库或使用它发送请求的方法。

在 python 中,我可以通过创建自定义 TCPConnector 来指定 TCP 家族类。

import aiohttp
import socket

conn = aiohttp.TCPConnector(family=socket.AF_INET6)

我在 Rust 中查看了相同的 TCPConnectorClientBuilder 内容。

Reqwest 的ClientBuilder 不支持它。见:https://docs.rs/reqwest/0.11.0/reqwest/struct.ClientBuilder.html

Hyper 的HTTPConnector 也不支持。见:https://docs.rs/hyper/0.14.4/hyper/client/struct.HttpConnector.html

【问题讨论】:

    标签: http tcp rust ipv6


    【解决方案1】:

    这不是很明显,但是如果您指定 local_address 选项,连接将使用该 IP 地址发送请求。

    我现在使用Reqwest(示例中为v0.11.1)。

    use std::net::IpAddr;
    use std::{collections::HashMap, str::FromStr};
    
    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        let client = reqwest::Client::builder()
            .local_address(IpAddr::from_str("2001:0db8:85a3:0000:0000:8a2e:0370:7334")?) 
            .build()?;
    
        let resp = client
            .get("https://httpbin.org/ip")
            .send()
            .await?
            .json::<HashMap<String, String>>()
            .await?;
    
        println!("{:#?}", resp);
        Ok(())
    }
    
    

    这也适用,但我现在更喜欢reqwest

    幸运的是,我找到了一个名为 isahc 的 HTTP 库,我可以指定 IP 版本。

    use isahc::{config::IpVersion, prelude::*, HttpClient};
    
    HttpClient::builder()
        .ip_version(IpVersion::V6)
    

    Isahc 的isahc::HttpClientBuilder 结构有ip_version 方法,您可以指定IP 版本。 (see)

    use isahc::{config::IpVersion, prelude::*, HttpClient};
    use std::{
        io::{copy, stdout},
        time::Duration,
    };
    
    fn main() -> Result<(), isahc::Error> {
        let client = HttpClient::builder()
            .timeout(Duration::from_secs(5))
            .ip_version(IpVersion::V6)
            .build()?;
    
        let mut response = client.get("some url")?;
    
        copy(response.body_mut(), &mut stdout())?;
    
        Ok(())
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多