Android開發(fā)獲取手機內(nèi)網(wǎng)IP地址與外網(wǎng)IP地址的詳細方法與源碼實例
在進行Android應(yīng)用開發(fā)過程中,有時候會遇到獲取當前Android設(shè)備所使用的網(wǎng)絡(luò)IP地址的場景,有時候需要本地的網(wǎng)絡(luò)IP地址,即局域網(wǎng)地址,更多的時候是需要當前網(wǎng)絡(luò)的真實的對外IP地址,即真實的網(wǎng)絡(luò)地址,如大數(shù)據(jù)分析時往往需要Android設(shè)備上傳本地的外網(wǎng)地址。本文對各種IP地址的獲取進行了總結(jié)。
首先用大家比較熟悉的電腦端局域網(wǎng)地址和外網(wǎng)地址的獲取方式對比一下:(1)、電腦端局域網(wǎng)地址獲取方式,可以通過在終端命令行輸入ipconfig進行查看,如下圖IPv地址標識的就是本機的局域網(wǎng)地址:
(2)、電腦端外網(wǎng)地址的獲取方式,可以通過在瀏覽器里面查詢,如在百度頁面搜索“IP地址查詢”查看本地外網(wǎng)地址,如下圖是筆者本機的外網(wǎng)地址:
本地IP地址有兩種情況:一是wifi下,二是移動網(wǎng)絡(luò)下
wifi下獲取本地局域網(wǎng)IP地址
// wifi下獲取本地網(wǎng)絡(luò)IP地址(局域網(wǎng)地址) 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 ""; }
移動網(wǎng)絡(luò)獲取網(wǎng)絡(luò)IP地址
// 獲取有限網(wǎng)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"; }
獲取外網(wǎng)地址非移動網(wǎng)絡(luò)
獲取Android設(shè)備的外網(wǎng)地址,即當前Wifi網(wǎng)絡(luò)真正的網(wǎng)絡(luò)地址,也即是網(wǎng)絡(luò)運營商分配給用戶的IP地址。
獲取外網(wǎng)地址的原理:通過訪問外網(wǎng)網(wǎng)站,從網(wǎng)站返回的數(shù)據(jù)中解析本地的IP地址。PS:在本地是無法獲取到外網(wǎng)的IP地址的,需要借助服務(wù)器。
/** * 獲取外網(wǎng)ip地址(非本地局域網(wǎng)地址)的方法 */ 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"); //設(shè)置瀏覽器ua 保證不出現(xiàn)503 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream in = connection.getInputStream(); // 將流轉(zhuǎn)化為字符串 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") + "區(qū)" + data.getString("region") + data.getString("city") + data.getString("isp") + ")"*/; Log.e(TAG, "您的IP地址是:" + ipAddress); } else { Log.e(TAG, "IP接口異常,無法獲取IP地址!"); } } else { Log.e(TAG, "網(wǎng)絡(luò)連接異常,無法獲取IP地址!"); } } catch (Exception e) { Log.e(TAG, "獲取IP地址時出現(xiàn)異常,異常信息是:" + e.toString()); } return ipAddress; }
根據(jù)網(wǎng)絡(luò)類型集成方法
@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網(wǎng)絡(luò) if (info.getType() == ConnectivityManager.TYPE_MOBILE) { return getHostIp(); } else if (info.getType() == ConnectivityManager.TYPE_WIFI) { // return getLocalIPAddress(context); // 局域網(wǎng)地址 return getOutNetIP(); // 外網(wǎng)地址 } else if (info.getType() == ConnectivityManager.TYPE_ETHERNET) { // 以太網(wǎng)有限網(wǎng)絡(luò) return getHostIp(); } } } catch (Exception e) { return ""; } return ""; }
下面在為大家提供兩個獲取手機IP地址的實例源碼
獲取內(nèi)網(wǎng)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; }
獲取外網(wǎng)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(); // 從反饋的結(jié)果中提取出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獲取手機內(nèi)網(wǎng)IP地址與外網(wǎng)IP地址的詳細方法與源碼實例,更多關(guān)于Android開發(fā)知識與技巧請查看下面的相關(guān)鏈接
相關(guān)文章
Android onActivityResult和setResult方法詳解及使用
這篇文章主要介紹了Android onActivityResult和setResult方法詳解及使用的相關(guān)資料,這里提供實例,幫助大家學習理解,需要的朋友可以參考下2016-12-12Android無障礙監(jiān)聽通知的實戰(zhàn)過程
開發(fā)微動手勢的時候,做了一個通知觸發(fā)的功能,就是在收到某個預設(shè)的通知的時候,自動觸發(fā)某個動作,因此需要監(jiān)聽通知消息,這篇文章主要給大家介紹了關(guān)于Android無障礙監(jiān)聽通知的相關(guān)資料,需要的朋友可以參考下2022-07-07講解Android中的Widget及AppWidget小工具的創(chuàng)建實例
這篇文章主要介紹了講解Android中的Widget及Widget的創(chuàng)建實例,文中的例子展示了通過RemoteView來溝通AppWidgetProvider與AppWidgetHostView的方法,需要的朋友可以參考下2016-03-03Android網(wǎng)絡(luò)編程之獲取網(wǎng)絡(luò)上的Json數(shù)據(jù)實例
這篇文章主要介紹了Android網(wǎng)絡(luò)編程之獲取網(wǎng)絡(luò)上的Json數(shù)據(jù)實例,本文用完整的代碼實例講解了在Android中讀取網(wǎng)絡(luò)中Json數(shù)據(jù)的方法,需要的朋友可以參考下2014-10-10Android錄制語音文件wav轉(zhuǎn)mp3的方法示例
這篇文章主要介紹了Android錄制語音文件wav轉(zhuǎn)mp3的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09android調(diào)用web service(cxf)實例應(yīng)用詳解
Google為ndroid平臺開發(fā)Web Service提供了支持,提供了Ksoap2-android相關(guān)架包接下來介紹android調(diào)用web service(cxf),感興趣的朋友可以了解下2013-01-01Android TextView實現(xiàn)跑馬燈效果的方法
這篇文章主要介紹了Android TextView跑馬燈效果實現(xiàn)方法,涉及Android布局文件中相關(guān)屬性的設(shè)置技巧,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-01-01