正如标题所说...我试图在将 wifi iface 配置为热点时获取其 IP。理想情况下,我想找到适用于所有手机的东西。
当然,WifiManager 在从 AP 获取信息时毫无用处。
幸运的是,我已经能够通过这样做来获取所有接口的 IP:
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
Log.d("IPs", inetAddress.getHostAddress() );
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
这段代码将打印所有接口的所有IP(包括Wifi热点)。主要问题是我没有找到识别WiFi接口的方法。这是一个问题,因为某些手机有多个接口(WiMax 等)。这是我到目前为止所尝试过的:
- 按 wifi iface 显示名称过滤:这不是一个好方法,因为显示名称从一个设备更改为另一个设备(wlan0、eth0、wl0.1 等)。
- 按 MAC 地址过滤:几乎可以工作,但在某些设备上,热点 iface 没有 MAC 地址( iface.getHardwareAddress() 返回 null)...所以不是有效的解决方案。
有什么建议么?
这是我获取 wifi 热点 ip 的方法:
public String getWifiApIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
if (intf.getName().contains("wlan")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&& (inetAddress.getAddress().length == 4)) {
Log.d(TAG, inetAddress.getHostAddress());
return inetAddress.getHostAddress();
}
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return null;
}
这将为您提供以下 IP 地址anywifi设备,这意味着它不仅仅用于热点。如果您连接到另一个 wifi 网络(意味着您未处于热点模式),它将返回一个 IP。
您应该先检查您是否处于 AP 模式。您可以使用此类:http://www.whitebyte.info/android/android-wifi-hotspot-manager-class http://www.whitebyte.info/android/android-wifi-hotspot-manager-class
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)