如何从 actix-web 中的 HttpRequest 检索客户端的 IP 地址?

How to retrieve the IP address of the client from HttpRequest in actix-web?

是否可以从 HttpRequest 参数中获取 IP 地址?

这是我的代码:

#[get("/collect")]
pub async fn collect(req: HttpRequest) -> impl Responder {
    println!("collect {:?}", req);
    HttpResponse::Ok()
}
[dependencies]
actix-web = "3"

如果服务前面没有代理,应该可以从请求中检索到 peer_addr()

否则,您可以检索请求 connection_info(), and from there, the realip_remote_addr()

示例:

#[get("/collect")]
pub async fn collect(req: HttpRequest) -> impl Responder {
    if let Some(val) = req.peer_addr() {
        println!("Address {:?}", val.ip());
    };
    HttpResponse::Ok()
}