brian
brian

Reputation: 6922

How to get gateway address on Android

I use this code to get gateway:

DhcpInfo d;
WifiManager wifii;
wifii= (WifiManager) getSystemService(Context.WIFI_SERVICE);
d=wifii.getDhcpInfo();
int gatewayip = d.gateway;

It works now, but DhcpInfo is deprecated as of API level 18.
Is there any other way to get the gateway address?

Upvotes: 2

Views: 6165

Answers (1)

ecle
ecle

Reputation: 4000

It suggests the use of ConnectivityManager.getLinkProperties as follows:

LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);

But, when I try to find more info about LinkProperties class, it is not available officially:

Anyway I found the following codes from here: http://ics-custom-settings.googlecode.com/git-history/65f22c5e653e1ee9767572d3ca938f9a1217801d/src/com/android/settings/Utils.java

/**
 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
 * @param context the application context
 * @return the formatted and comma-separated IP addresses, or null if none.
 */
public static String getWifiIpAddresses(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
    return formatIpAddresses(prop);
}

/**
 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
 * addresses.
 * @param context the application context
 * @return the formatted and comma-separated IP addresses, or null if none.
 */
public static String getDefaultIpAddresses(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    LinkProperties prop = cm.getActiveLinkProperties();
    return formatIpAddresses(prop);
}

private static String formatIpAddresses(LinkProperties prop) {
    if (prop == null) return null;
    Iterator<InetAddress> iter = prop.getAddresses().iterator();
    // If there are no entries, return null
    if (!iter.hasNext()) return null;
    // Concatenate all available addresses, comma separated
    String addresses = "";
    while (iter.hasNext()) {
        addresses += iter.next().getHostAddress();
        if (iter.hasNext()) addresses += ", ";
    }
    return addresses;
}

Update! Ok, I found LinkProperties class over here http://developer.oesf.biz/em/developer/reference/eggplant/android/net/LinkProperties.html

Upvotes: 1

Related Questions