6

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"
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

1 Answers1

8

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()
}
John Ledbetter
  • 13,557
  • 1
  • 61
  • 80
  • SHould I call peer_addr(req) ? I'm rust begginer, it is not obvious for me – captain-yossarian from Ukraine Apr 07 '21 at 16:20
  • 1
    @captain-yossarian you'd typically just do `req.peer_addr()` – kmdreko Apr 07 '21 at 17:23
  • @JohnLedbetter Maybe adding a security warning about the fact that ip adress returned by `realip_remote_addr()` can be spoofed. – Jerboas86 Nov 09 '21 at 15:24
  • 2
    @captain-yossarian normally in a real (production) environment, clients don't connect directly to your web server. Instead they connect to something called a "reverse proxy," which is just a different server that takes requests and forwards them onto the server you built (in which case you would need to use `real_remote_addr`). Purposes of the reverse proxy might include 1) increasing security (requests can be scanned or filtered by the proxy), 2) load balancing (distributing requests across multiple instances of your server), or 3) serving up static files like CSS stylesheets and images. – tedtanner Jan 29 '22 at 17:19
  • @tedtanner thank you for thorough explanation – captain-yossarian from Ukraine Jan 29 '22 at 18:34