项目中用到获取IP,从网上找了个方法,刚开始用手机移动网的时候,可以获取正确的IP,后来用wifi来调试获取了一连串数字,并且数字太长导致后台入库错误。
后来,发现wifi状态下获取的IP是要经过转换的,在这里提供一个转换后的方法:
// Get IP address
public static String getLocalIpAddress(Context context)
{
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
WifiManager wifimanage = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);// 获取WifiManager
// 检查wifi是否开启
if (!wifimanage.isWifiEnabled()) {
}
WifiInfo wifiinfo = wifimanage.getConnectionInfo();
// 将获取的int转为真正的ip地址,参考的网上的,修改了下
int i = wifiinfo.getIpAddress();
return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
} else if (mobile.isAvailable()) {
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 e) {
e.printStackTrace();
}
}
return null;
}
经过测试方法可用,并且ip转换正确。