Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind gRPC service to localhost in Java

I have a gRPC service which I would just like to bind just to the localhost address. However, I don't see a way to do that in Java. Instead it will bind to all addresses.

Here is how I create my service now:

server = ServerBuilder.forPort(config.port())
                      .addService(new GRPCServiceImpl(serviceParams))
                      .build()
                      .start();
LOG.info("Server started, listening on " + config.port());

There doesn't seem to be an API exposed on ServerBuilder or Server which allows specifying the address or network interface. Whereas the C++ API has AddListentingPort.

So is there a way in Java to restrict which IP or interface the service listens on?

like image 725
Dusty Campbell Avatar asked Nov 15 '16 21:11

Dusty Campbell


People also ask

How do you write a gRPC service in Java?

You need to use the proto3 compiler (which supports both proto2 and proto3 syntax) in order to generate gRPC services. When using Gradle or Maven, the protoc build plugin can generate the necessary code as part of the build. You can refer to the grpc-java README for how to generate code from your own . proto files.

How does gRPC work in Java?

grpc; The first line tells the compiler what syntax is used in this file. By default, the compiler generates all the Java code in a single Java file. The second line overrides this setting, and everything will be generated in individual files.


1 Answers

You can do this by picking a more specific ServerBuilder, such as the NettyServerBuilder:

NettyServerBuilder.forAddress(new InetSocketAddress("localhost", config.port()))
    .addService(new GRPCServiceImpl(serviceParams))
    .build()
    .start();
like image 79
Carl Mastrangelo Avatar answered Oct 04 '22 13:10

Carl Mastrangelo