如何在Android上获取网关地址

如何在Android上获取网关地址,android,Android,我使用此代码获取网关: DhcpInfo d; WifiManager wifii; wifii= (WifiManager) getSystemService(Context.WIFI_SERVICE); d=wifii.getDhcpInfo(); int gatewayip = d.gateway; 它现在可以工作了,但是从API级别18起,DhcpInfo就被弃用了。 有没有其他方法获取网关地址 建议使用ConnectivityManager.getLinkProperties如下:

我使用此代码获取网关:

DhcpInfo d;
WifiManager wifii;
wifii= (WifiManager) getSystemService(Context.WIFI_SERVICE);
d=wifii.getDhcpInfo();
int gatewayip = d.gateway;
它现在可以工作了,但是从API级别18起,
DhcpInfo
就被弃用了。

有没有其他方法获取网关地址

建议使用ConnectivityManager.getLinkProperties如下:

LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
但是,当我试图查找有关LinkProperties类的更多信息时,官方并未提供:

无论如何,我在这里找到了以下代码:

/**
*返回WIFI IP地址(如果有),考虑IPv4和IPv6样式的地址。
*@param context应用程序上下文
*@返回格式化和逗号分隔的IP地址,如果没有,则返回null。
*/
公共静态字符串getWifiIpAddresses(上下文){
ConnectionManager cm=(ConnectionManager)
getSystemService(context.CONNECTIVITY\u服务);
LinkProperties prop=cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
返回formatIpAddresses(prop);
}
/**
*返回默认链接的IP地址(如果有),并考虑IPv4和IPv6样式
*地址。
*@param context应用程序上下文
*@返回格式化和逗号分隔的IP地址,如果没有,则返回null。
*/
公共静态字符串getDefaultIpAddresses(上下文){
ConnectionManager cm=(ConnectionManager)
getSystemService(context.CONNECTIVITY\u服务);
LinkProperties prop=cm.getActiveLinkProperties();
返回formatIpAddresses(prop);
}
专用静态字符串格式IP地址(LinkProperties属性){
if(prop==null)返回null;
迭代器iter=prop.getAddresses().Iterator();
//如果没有条目,则返回null
if(!iter.hasNext())返回null;
//连接所有可用地址,逗号分隔
字符串地址=”;
while(iter.hasNext()){
地址+=iter.next().getHostAddress();
if(iter.hasNext())地址+=“,”;
}
返回地址;
}
更新
好的,我在这里找到了LinkProperties

它建议使用ConnectivityManager.getLinkProperties如下:

LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
但是,当我试图查找有关LinkProperties类的更多信息时,官方并未提供:

无论如何,我在这里找到了以下代码:

/**
*返回WIFI IP地址(如果有),考虑IPv4和IPv6样式的地址。
*@param context应用程序上下文
*@返回格式化和逗号分隔的IP地址,如果没有,则返回null。
*/
公共静态字符串getWifiIpAddresses(上下文){
ConnectionManager cm=(ConnectionManager)
getSystemService(context.CONNECTIVITY\u服务);
LinkProperties prop=cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
返回formatIpAddresses(prop);
}
/**
*返回默认链接的IP地址(如果有),并考虑IPv4和IPv6样式
*地址。
*@param context应用程序上下文
*@返回格式化和逗号分隔的IP地址,如果没有,则返回null。
*/
公共静态字符串getDefaultIpAddresses(上下文){
ConnectionManager cm=(ConnectionManager)
getSystemService(context.CONNECTIVITY\u服务);
LinkProperties prop=cm.getActiveLinkProperties();
返回formatIpAddresses(prop);
}
专用静态字符串格式IP地址(LinkProperties属性){
if(prop==null)返回null;
迭代器iter=prop.getAddresses().Iterator();
//如果没有条目,则返回null
if(!iter.hasNext())返回null;
//连接所有可用地址,逗号分隔
字符串地址=”;
while(iter.hasNext()){
地址+=iter.next().getHostAddress();
if(iter.hasNext())地址+=“,”;
}
返回地址;
}
更新
好的,我在这里找到了LinkProperties类,请注意:
LinkProperties
在API 18下…请检查android支持库。请注意:
LinkProperties
在API 18下…请检查android支持库。