You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在新版reqwest中获取本地与远程SockAddr?

在reqwest 0.12中获取本地/远程套接字地址的方法

在reqwest 0.12及配套的新版hyper中,原hyper::client::connect::HttpInfo已被移除,取而代之的是hyper::client::connect::Connected类型,reqwest也对该类型进行了重导出,可直接通过它获取连接的套接字地址信息。

实现方案

  • 导入reqwest提供的Connected类型(对应hyper的同名类型)
  • 通过响应的扩展信息获取Connected实例
  • 调用实例的local_addr()和remote_addr()方法获取套接字地址,注意这两个方法返回Option<SocketAddr>,需处理空值场景

完整代码示例

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
    let response = reqwest::Client::new()
        .get("https://example.com/")
        .send()
        .await?
        .error_for_status()?;

    let connected = response
        .extensions()
        .get::<reqwest::connect::Connected>()
        .ok_or(anyhow::anyhow!("无法获取套接字地址信息"))?;

    // 打印本地地址
    if let Some(local_addr) = connected.local_addr() {
        println!("本地套接字地址: {}", local_addr);
    } else {
        eprintln!("无法获取本地套接字地址");
    }

    // 打印远程地址
    if let Some(remote_addr) = connected.remote_addr() {
        println!("远程套接字地址: {}", remote_addr);
    } else {
        eprintln!("无法获取远程套接字地址");
    }

    println!("响应内容: {}", response.text().await?);

    Ok(())
}

关键说明

  • local_addr()和remote_addr()返回Option是因为部分连接场景(如非TCP协议连接)可能无法提供这些地址信息
  • 确保Cargo.toml中reqwest版本为0.12+,并根据需要启用运行时特性(如tokio)

内容的提问来源于stack exchange,提问作者takaomag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 00:12:22