Hyper: Provide access to remote IP address in incoming server requests

Created on 7 Sep 2018  路  5Comments  路  Source: hyperium/hyper

When writing a server in Hyper I should be able to retrieve the remote IP address from the request.

@seanmonstar mentioned in #1410 that an API similar to the client (#1402) might be relevant?

API usage could then look like this:

fn respond_with_sender_ip(request: Request<Body>) -> BoxFut {
    let remote_address = request
        .extensions()
        .get::<HttpInfo>()
        .expect("something something sets HttpInfo")
        .remote_addr();

    Box::new(future::ok(Response::new(Body::from(remote_address))))
}

(Please edit this to make the proposed API usage correct :-)

A-server B-upstream S-feature

Most helpful comment

I did some exploration of converting NewService to MakeService<Ctx>, such that you can access the transport when creating a Service. The WIP is here: https://github.com/hyperium/hyper/commit/94cc8065490497dcaf6bbb9862c0b1f28bf10126

Here's how the API worked out (mostly so as to not be a breaking change for NewService):

let server = Server::bind(&addr)
    .serve(make_service_fn(|conn: &AddrStream| {
        let remote_addr = conn.remote_addr();
        service_fn_ok(move |_: Request<Body>| {
            Response::new(Body::from(format!("Hello, {}", remote_addr)))
        })
    }))

All 5 comments

+1 for this request, ip address info is very useful for a network service

The idea of passing an argument to the NewService is being explored here: https://github.com/tower-rs/tower/issues/108

If that change is done, we could pass &Incoming::Item or something, and then the NewService could grab the remote address and anything else it wants (like TLS context info) to then be used in the constructed Services.

I did some exploration of converting NewService to MakeService<Ctx>, such that you can access the transport when creating a Service. The WIP is here: https://github.com/hyperium/hyper/commit/94cc8065490497dcaf6bbb9862c0b1f28bf10126

Here's how the API worked out (mostly so as to not be a breaking change for NewService):

let server = Server::bind(&addr)
    .serve(make_service_fn(|conn: &AddrStream| {
        let remote_addr = conn.remote_addr();
        service_fn_ok(move |_: Request<Body>| {
            Response::new(Body::from(format!("Hello, {}", remote_addr)))
        })
    }))

I'm working on a reverse proxy using hyper (new version for https://github.com/brendanzab/hyper-reverse-proxy), and this is quite useful to implement x-forwarded-for header. The former version was hooked directly to TcpListener, which is quite low level.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zonyitoo picture zonyitoo  路  4Comments

crackcomm picture crackcomm  路  5Comments

lslima91 picture lslima91  路  4Comments

alex picture alex  路  4Comments

Firstyear picture Firstyear  路  4Comments