Android開發獲取手機內網IP地址與外網IP地址的詳細方法與原始碼例項
阿新 • • 發佈:2020-03-20
在進行Android應用開發過程中,有時候會遇到獲取當前Android裝置所使用的網路IP地址的場景,有時候需要本地的網路IP地址,即區域網地址,更多的時候是需要當前網路的真實的對外IP地址,即真實的網路地址,如大資料分析時往往需要Android裝置上傳本地的外網地址。本文對各種IP地址的獲取進行了總結。
首先用大家比較熟悉的電腦端區域網地址和外網地址的獲取方式對比一下:(1)、電腦端區域網地址獲取方式,可以通過在終端命令列輸入ipconfig進行檢視,如下圖IPv地址標識的就是本機的區域網地址:
(2)、電腦端外網地址的獲取方式,可以通過在瀏覽器裡面查詢,如在百度頁面搜尋“IP地址查詢”檢視本地外網地址,如下圖是筆者本機的外網地址:
本地IP地址有兩種情況:一是wifi下,二是行動網路下
wifi下獲取本地區域網IP地址
// wifi下獲取本地網路IP地址(區域網地址) public static String getLocalIPAddress(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { @SuppressLint("MissingPermission") WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ipAddress = intIP2StringIP(wifiInfo.getIpAddress()); return ipAddress; } return ""; }
行動網路獲取網路IP地址
// 獲取有限網IP public static String getHostIp() { 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(); } } } } catch (Exception ex) { } return "0.0.0.0"; }
獲取外網地址非行動網路
獲取Android裝置的外網地址,即當前Wifi網路真正的網路地址,也即是網路運營商分配給使用者的IP地址。
獲取外網地址的原理:通過訪問外網網站,從網站返回的資料中解析本地的IP地址。PS:在本地是無法獲取到外網的IP地址的,需要藉助伺服器。
/** * 獲取外網ip地址(非本地區域網地址)的方法 */ public static String getOutNetIP() { String ipAddress = ""; try { String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip"; URL url = new URL(address); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setUseCaches(false); connection.setRequestMethod("GET"); connection.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/51.0.2704.7 Safari/537.36"); //設定瀏覽器ua 保證不出現503 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream in = connection.getInputStream(); // 將流轉化為字串 BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String tmpString; StringBuilder retJSON = new StringBuilder(); while ((tmpString = reader.readLine()) != null) { retJSON.append(tmpString + "\n"); } JSONObject jsonObject = new JSONObject(retJSON.toString()); String code = jsonObject.getString("code"); Log.e(TAG,"提示:" +retJSON.toString()); if (code.equals("0")) { JSONObject data = jsonObject.getJSONObject("data"); ipAddress = data.getString("ip")/* + "(" + data.getString("country") + data.getString("area") + "區" + data.getString("region") + data.getString("city") + data.getString("isp") + ")"*/; Log.e(TAG,"您的IP地址是:" + ipAddress); } else { Log.e(TAG,"IP介面異常,無法獲取IP地址!"); } } else { Log.e(TAG,"網路連線異常,無法獲取IP地址!"); } } catch (Exception e) { Log.e(TAG,"獲取IP地址時出現異常,異常資訊是:" + e.toString()); } return ipAddress; }
根據網路型別整合方法
@SuppressLint("MissingPermission") public static String getIpAddress(Context context) { if (context == null) { return ""; } ConnectivityManager conManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); try { NetworkInfo info = conManager.getActiveNetworkInfo(); if (info != null && info.isConnected()) { // 3/4g網路 if (info.getType() == ConnectivityManager.TYPE_MOBILE) { return getHostIp(); } else if (info.getType() == ConnectivityManager.TYPE_WIFI) { // return getLocalIPAddress(context); // 區域網地址 return getOutNetIP(); // 外網地址 } else if (info.getType() == ConnectivityManager.TYPE_ETHERNET) { // 乙太網有限網路 return getHostIp(); } } } catch (Exception e) { return ""; } return ""; }
下面在為大家提供兩個獲取手機IP地址的例項原始碼
獲取內網IP地址
/** * 獲取ip地址 * @return */ public static String getHostIP() { String hostIp = null; try { Enumeration nis = NetworkInterface.getNetworkInterfaces(); InetAddress ia = null; while (nis.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) nis.nextElement(); Enumeration<InetAddress> ias = ni.getInetAddresses(); while (ias.hasMoreElements()) { ia = ias.nextElement(); if (ia instanceof Inet6Address) { continue;// skip ipv6 } String ip = ia.getHostAddress(); if (!"127.0.0.1".equals(ip)) { hostIp = ia.getHostAddress(); break; } } } } catch (SocketException e) { Log.i("yao","SocketException"); e.printStackTrace(); } return hostIp; }
獲取外網IP地址
/** * 獲取IP地址 * @return */ public static String GetNetIp() { URL infoUrl = null; InputStream inStream = null; String line = ""; try { infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8"); URLConnection connection = infoUrl.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { inStream = httpConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"utf-8")); StringBuilder strber = new StringBuilder(); while ((line = reader.readLine()) != null) strber.append(line + "\n"); inStream.close(); // 從反饋的結果中提取出IP地址 int start = strber.indexOf("{"); int end = strber.indexOf("}"); String json = strber.substring(start,end + 1); if (json != null) { try { JSONObject jsonObject = new JSONObject(json); line = jsonObject.optString("cip"); } catch (JSONException e) { e.printStackTrace(); } } return line; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return line; }
本文主要講解了Android獲取手機內網IP地址與外網IP地址的詳細方法與原始碼例項,更多關於Android開發知識與技巧請檢視下面的相關連結