Dusty Campbell
Dusty Campbell

Reputation: 3156

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?

Upvotes: 7

Views: 3625

Answers (1)

Carl Mastrangelo
Carl Mastrangelo

Reputation: 6628

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();

Upvotes: 15

Related Questions