起初我試着去取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,發現了這一點。 –