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

Viewed 1982

Is it possible to obtain the IP address from a HttpRequest argument?

This is my code:

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

If you do not have a proxy in front of the service, it should be retrievable from the request peer_addr().

Otherwise, you can retrieve the request connection_info(), and from there, the realip_remote_addr().

Example:

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