问题描述
我正在尝试使用 IPv6 发送 HTTP 请求。
虽然有很多 HTTP 库(reqwest、hyper 等)。我找不到图书馆或通过它发送请求的方式。
在 python 中,我能够通过创建自定义 TCPConnector 来指定 TCP 家族类。
import aiohttp
import socket
conn = aiohttp.TCPConnector(family=socket.AF_INET6)
我在 Rust 中浏览了相同的 TCPConnector
、ClientBuilder
事物。
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
解决方法
这并不明显,但如果您指定 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,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(())
}