在wifi环境下,可以通过WifiInfo来获取设备的ip
执行上面的代码需要
当然也可通过jdk总的NetworkInterface来获取的,就是遍历所有的网络接口,获取到非loopback ip
public String getIpAddress() {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
int[] ipAddr = new int[4];
ipAddr[0] = ipAddress & 0xFF;
ipAddr[1] = (ipAddress >> 8) & 0xFF;
ipAddr[2] = (ipAddress >> 16) & 0xFF;
ipAddr[3] = (ipAddress >> 24) & 0xFF;
return new StringBuilder().append(ipAddr[0]).append(".").append(ipAddr[1]).append(".").append(ipAddr[2])
.append(".").append(ipAddr[3]).append(".").toString();
}
执行上面的代码需要
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
当然也可通过jdk总的NetworkInterface来获取的,就是遍历所有的网络接口,获取到非loopback 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()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("", ex.toString());
}
return null;
}