android 獲取正確IP

       項目中用到獲取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轉換正確。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章