rustreqwest

Rust reqwest: How to get local and remote SockAddr?


I want to get local/remote SockAddr pair of a successful reqwest http connection.

I used to write the following code.

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

    let http_info = response
        .extensions()
        .get::<hyper::client::connect::HttpInfo>()
        .ok_or(anyhow::anyhow!("failed to collect socket addresses"))?;

    println!("sock_local_addr: {}", http_info.local_addr());
    println!("sock_remote_addr: {}", http_info.remote_addr());
    println!("response text: {}", response.text().await?);

    Ok(())
}

In case of old reqwest and hyper (reqwest==0.11, hyper==0.14), it works well.

But latest hyper does not have hyper::client::connect::HttpInfo, and reqwest 0.11 is a little stale.

Is there any proper way to get local/remote socket addresses in latest reqwest version?


In case of reqwest 0.12,

response
    .extensions()
    .get::<hyper::client::connect::HttpInfo>()

does not return Some::<HttpInfo>, but returns None (it can not get SocketAddr).


Solution

  • As documented in hyper's Upgrade from v0.14 to v1 guide:

    Client

    The higher-level pooling Client was removed from hyper 1.0. A similar type was added to hyper-util, called client::legacy::Client. It’s mostly a drop-in replacement.

    You'll find hyper_util::client::legacy::connect::HttpInfo in there too.