Let’s imagine that we need to get the client’s ip address from the request.
We have a service:
public class YourServiceImpl extends YourService.YourServiceImplBase {
@Override
public void yourMethod() {
...
}
}
And the code for starting the gRPC server:
Server server = ServerBuilder
.forPort(1234)
.addService(new YourServiceImpl())
.build();
server.start();
server.awaitTermination();
Let’s create a new class:
class IPInterceptor implements ServerInterceptor {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
String ipAddress = call.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR).toString();
log.warn("Client IP address = {}", ipAddress);
return next.startCall(call, headers);
}
}
And register a new interceptor in the gRPC server launch code:
Server server = ServerBuilder
.forPort(1234)
.addService(new YourServiceImpl())
.intercept(new IPInterceptor())
.build();
server.start();
server.awaitTermination();
Done. If you need to pass the ip address from the interceptor to the YourServiceImpl service, then read this article: https://mchesnavsky.tech/share-data-between-interceptor-and-service-grpc.
If you still have any questions, feel free to ask me in the comments under this article, or write me on promark33@gmail.com.