If I have an handler:
#[get("/")]
fn indexhandler() -> Result<Redirect, String>{
Ok(Redirect::to("/a"))
}
How do I get the remote IP?
Rocket v0.2.6
rustc 1.18.0-nightly (94e884b63 2017-04-27)
Specifics would help, what ip are you looking for? The clients? The Servers? Please feel free to include more details, will make it much easier to help you.
I need the client's IP.
You Have to tell rocket to pass your handler the raw request, then you can access the remote socket address, like this.
#[get("/")]
fn index(req: Request) -> String {
let remote_socket_addr = req.remote().unwrap();
format!("Ip: {:?}",remote_socket_addr)
}
@bytebuddha's answer is close, but you should never, _ever_ be unwrapping request related content in a handler. This is one of the core strength's of Rocket: all request data should be validated _before_ a handler is called.
The correct thing to do is use to use the SocketAddr request guard, as documented in the FromRequest page, as follows:
#[get("/")]
fn index(remote_addr: SocketAddr) -> String {
format!("Remote Address: {:?}", remote_addr)
}
@SergioBenitez And how would I do this if I have a handler that accepts data (like a String)?
Never mind, I was able to do it. Thank you so much @SergioBenitez, @bytebuddha, and @SirDoctors.