use*_*350 10 android ip-address wifi android-networking android-wifi
我需要在托管热点时找到设备的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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这工作得很好但是NetworkInterface某些设备上的wifi 名称不同.所以我必须首先找到设备的wifi NetworkInterface名称(针对其热点).我怎么能找到这个名字?或者是否有更好的方法来查找设备的IP地址?
///通过MAC查找正确的IP地址似乎也不起作用
flx*_*flx 11
起初我尝试获取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;
}
Run Code Online (Sandbox Code Playgroud)
只有一个接口符合所有条件:wlan0.
可能的其他方案:
走一些最常见的接口名称并尝试在列表中找到它们: new String[] { "wlan0", "eth0", ...];
我最近发现WifiAP IP地址在Android中是硬编码的.除非用户手动更改此值(我认为这是非常罕见的)使用硬编码值绝对足够.我认为这是最好的方式.IP地址为"192.168.43.1":https://github.com/CyanogenMod/android_frameworks_base/blob/cm-10.1/wifi/java/android/net/wifi/WifiStateMachine.java?source=c#L1299