http - 在 Rust 中发送 HTTP 请求时如何使用 IF_INET6 - IPV6
问题描述
我正在尝试使用 IPv6 发送 HTTP 请求。
虽然有很多 HTTP 库(reqwest、hyper等)。我找不到图书馆或用它发送请求的方法。
在 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
解决方案
这并不明显,但如果您指定 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
struct 具有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(())
}
推荐阅读
- c# - 并行运行测试时如何将日志写入不同的文件?
- firebase - firebase auth onCreate 触发器应该有更多数据吗?
- recaptcha - Google 的 RuntimeConfig API 响应“我们的系统检测到来自您的计算机网络的异常流量”
- python - 运行 django 时出现错误
- npm - 在同一个控制台上使用 ng build watch 和 gulp watch
- r - 在 R 中进行带有数据可视化的 Scala 数学模拟时,如何最好地处理大数据?
- python - 我怎样才能打印这样的输出列表
- css - 如何使引导容器在古腾堡工作
- angular - 忽略 .gitignore 中名为 npm-debug.log.XXXXXX 的文件
- java - java.lang.NullPointerException:尝试调用虚拟方法'java.lang.String com.example.ghifa.mrad.Model.User.getImageurl()'