androidroutetable

Android: get route info programmatically


I am sending UDP packets to a remote, and I would like to know the IP of the local interface that will be used for that. In a shell I would run:

ip route get 192.168.1.54

and it would answer something like:

192.168.1.12 dev wlan0  table local_network  src 192.168.1.1

Where I'm interested in getting the src: 192.168.1.1.

I can do it by calling exec like this:

Runtime.getRuntime().exec("ip route get 192.168.1.54")

but that does not seem very elegant and I don't know which devices support that (it works on some of them, and others return an error code "1" though the command works in adb shell).

Is there a way to do that with the Android SDK? I looked at the ConnectivityManager but could not find a way...


Solution

  • It looks like you want the address of the network's gateway for your WiFi network.

    This function is based on doc and some examples.

    public InetAddress getGateway(Context context) {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            // getActiveNetwork() requires M or later.
            return null;
        }
        Network activeNetwork = connectivityManager.getActiveNetwork();
        if (activeNetwork == null) {
            return null;
        }
        List<RouteInfo> routes = connectivityManager.getLinkProperties(activeNetwork).getRoutes();
        for (RouteInfo route : routes) {
            if (route.isDefaultRoute() && !(route.getGateway() instanceof Inet6Address)) {
               return route.getGateway();
            }
        }
        return null;
    }