tower-rs / tower-grpc

A gRPC client & server implementation.
MIT License
562 stars 73 forks source link

How to got the address of the client which the RPC being serviced? #168

Closed songsenand closed 5 years ago

songsenand commented 5 years ago

In fact, I need to implement a whitelist function. I tried to found a function which can get the client's address in the source code but could not find it. So... is there a function that can get the client's address when the client connects? Thanks for your time!

seanmonstar commented 5 years ago

If we look at the Greeter server example, we can adjust the Greet type to hold a SocketAddr. Then, you can construct a Greet only once a connection is received, and grab the peer address.

let serve = bind
    .incoming()
    .for_each(move |sock| {
        // set_nodelay, etc
        // ...

        match sock.peer_addr() {
            Ok(addr) => {
                let greet = Greet(addr);
                let server = Server::new(server::GreeterServer::new(greet));
                // etc...
            },
            Err(_) => {
                // socket already disconnected, so just skip
                Ok(())
            }
        }
    });
}