如何在Android上获取网关地址

时间:2013-09-26 01:30:20

标签: android

我使用此代码获取网关:

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

现在可以使用,但从API级别18开始,DhcpInfo已弃用。
有没有其他方法来获取网关地址?

1 个答案:

答案 0 :(得分:1)

建议使用 ConnectivityManager.getLinkProperties ,如下所示:

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

但是,当我尝试查找有关 LinkProperties 类的更多信息时,它无法正式提供:

无论如何,我从这里找到了以下代码: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;
}

更新! 好的,我在http://developer.oesf.biz/em/developer/reference/eggplant/android/net/LinkProperties.html

找到了 LinkProperties 课程