Search code examples
android.netnetwork-programminggrpc

How can I call a gRPC server running on a local network PC from a client Android app?


On my laptop, I have a gRPC server running in a .NET 6 application, using Grpc.AspNetCore 2.40.0. On my phone, I have an .NET 6 Android app built using the Uno UI framework, using the gRPC client GRPC.Net.Client 2.46.0. Both are on the same local network.

I would like to be able connect to the gRPC server from the phone app.

When I try to connect in the app, it fails with the error:

{ManagedException, High : Status(StatusCode="Unavailable", Detail="Error connecting to subchannel.", DebugException="System.Net.Sockets.SocketException (110): Connection timed out
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
   at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
   at Grpc.Net.Client.Balancer.Internal.SocketConnectivitySubchannelTransport.TryConnectAsync(CancellationToken cancellationToken) in /_/src/Grpc.Net.Client/Balancer/Internal/SocketConnectivitySubchannelTransport.cs:line 138")}

If, instead of this setup, I am running the app in any of these configurations:

  • Windows app running on the same PC
  • Android app running on an emulator on the same PC
  • Android app running on the phone connected to the PC via USB, using adb reverse tcp:8080 tcp:7773 to talk to the PC over the USB

Then the connection is successful, so I know the problem is something specific to trying to connect over the network.

I am able to ping my PC's local network IP from my android phone. gRPC is not using https, the client is trying to connect to http://192.168.0.246:7773. Is this the right address? I also tried just using 192.168.0.246:7771 but this resulted in the gRPC client failing to be created in the first place.

I've tried using Windows Firewall to open the relevant inbound connection ports, but I don't know much about this. Is there something that needs to be done with the firewall? The gRPC server is running on port 7773.

Is there anything else that needs to be done to allow gRPC clients to connect over a local network?

Thanks!


Solution

  • Figured it out. My server was listening on localhost, which means it was only listening for connections coming from the same device. To listen for any connections, I had to update it to listen on 0.0.0.0.

    For the ASP.NET web server I am using, this was done by updating the call to ConfigureKestrel to use the ListenAnyIP option rather than the ListenLocalhost option.

    To help with debugging this I used Wireshark and netstat -ab.