gRPC request get client IP


What's inside this article ⌄
  • GRPC get client IP address from request
  • GRPC client address
  • GRPC client IP
  • GRPC request IP

Let’s imagine that we need to get the client’s ip address from the request.

We have a service YourServiceImpl.java:

public class YourServiceImpl extends YourService.YourServiceImplBase {
  @Override 
  public void yourMethod() {
		...
	}
}

And the code for starting the gRPC server GRPCServer.java:

Server server = ServerBuilder
    .forPort(1234)
    .addService(new YourServiceImpl())
    .build();
server.start();
server.awaitTermination();

Let’s create a new class IPInterceptor.java:

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 GRPCServer.java:

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.