当设备托管热点时,我需要找到设备的 IP 地址。到目前为止我已经使用过这段代码:
//if is using Hotspot
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)) {
return inetAddress.getHostAddress();
}
}
}
}
这工作得很好,但无线网络NetworkInterface
名称在某些设备上有所不同。所以我必须找到设备的wifiNetworkInterface
首先是名称(其热点)。我怎样才能找到这个名字?或者有更好的方法来查找设备的IP地址吗?
/// 通过MAC找到正确的IP地址似乎也不起作用
首先我尝试获取WiFi接口的MAC地址,并将其与每个接口的MAC地址进行比较。但事实证明,至少在我运行 CM 的 N4 上,打开热点时 WiFi 接口的 MAC 会发生变化。
因此,我编写了一些代码来遍历设备列表,以找到可识别 wifi 接口的内容。这段代码在我的 N4 上完美运行:
private String getWifiIp() throws SocketException {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
if (intf.isLoopback()) {
continue;
}
if (intf.isVirtual()) {
continue;
}
if (!intf.isUp()) {
continue;
}
if (intf.isPointToPoint()) {
continue;
}
if (intf.getHardwareAddress() == null) {
continue;
}
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (inetAddress.getAddress().length == 4) {
return inetAddress.getHostAddress();
}
}
}
return null;
}
只有一个接口符合所有条件:wlan0
.
可能的其他解决方案:
浏览一些最常见的接口名称并尝试在列表中找到它们:new String[] { "wlan0", "eth0", ...];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)