起初我试着去取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
。
其它可能的解决方案:
走线槽一些最常用的接口的名字,并试图找到它们在列表中:在oncreat
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()) {
String ip = Formatter.formatIpAddress(inetAddress.hashCode());
Toast.makeText(getApplicationContext(), "***** IP="+ ip, 1).show();
return ip;
}
}
}
} catch (SocketException ex) {
Toast.makeText(getApplicationContext(), "***** IP="+ex.toString(), 1).show();
}
return null;
}
写代码:new String[] { "wlan0", "eth0", ...];
来源
2014-02-23 13:12:16
flx
没有为我工作(在HTC One上)。当我设置一个Wifi热点时,我的手机的IP为192.168.1.1。我通过连接到Windows盒子的热点并通过'ipconfig/all'检查Wi-Fi网关IP,发现了这一点。 –