很多地方需要用到用户手机的IP地址
/**
* 用户登陆IP地址
*
* @return ip
*/
private String getMobileIP() {
if (!"".equals(getLocalIpAddress())) {
return getLocalIpAddress();
}
return getIpAddress();
}
/**
* 获取WIFI设备IP
*
* @return IP
*/
private String getIpAddress() {
//获取wifi服务
WifiManager wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//判断wifi是否开启
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = intToIp(ipAddress);
return ip;
}
private static String intToIp(int i) {
return (i & 0xFF) + "." +
((i >> 8) & 0xFF) + "." +
((i >> 16) & 0xFF) + "." +
(i >> 24 & 0xFF);
}
/**
* 获取网络设备IP
*
* @return IP
*/
private static 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() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Logout.e("WifiPreference IpAddress", ex.toString());
}
return "";
}