首页 > 解决方案 > 在 Rust 中发送 HTTP 请求时如何使用 IF_INET6 - IPV6

问题描述

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

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

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

import aiohttp
import socket

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

我在 Rust 中查看了相同TCPConnector的东西。ClientBuilder

ReqwestClientBuilder不支持它。请参阅:https ://docs.rs/reqwest/0.11.0/reqwest/struct.ClientBuilder.html

HyperHTTPConnector也不支持。请参阅:https ://docs.rs/hyper/0.14.4/hyper/client/struct.HttpConnector.html

标签: httptcprustipv6

解决方案


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

我现在使用Reqwestv0.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::HttpClientBuilderstruct 具有ip_version可以指定 IP 版本的方法。(

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

推荐阅读