2

我使用此代码获取网关:

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

它现在可以工作,但从DhcpInfoAPI 级别 18 起已弃用。
还有其他方法可以获取网关地址吗?

4

1 回答 1

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;
}

更新! 好的,我在这里找到了LinkPropertieshttp://developer.oesf.biz/em/developer/reference/eggplant/android/net/LinkProperties.html

于 2013-09-26T04:21:29.377 回答