Android開發(fā)如何獲取手機(jī)內(nèi)網(wǎng)IP地址與外網(wǎng)IP地址

這篇文章將為大家詳細(xì)講解有關(guān)Android開發(fā)如何獲取手機(jī)內(nèi)網(wǎng)IP地址與外網(wǎng)IP地址,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

創(chuàng)新互聯(lián)憑借在網(wǎng)站建設(shè)、網(wǎng)站推廣領(lǐng)域領(lǐng)先的技術(shù)能力和多年的行業(yè)經(jīng)驗(yàn),為客戶提供超值的營銷型網(wǎng)站建設(shè)服務(wù),我們始終認(rèn)為:好的營銷型網(wǎng)站就是好的業(yè)務(wù)員。我們已成功為企業(yè)單位、個(gè)人等客戶提供了成都網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)、外貿(mào)營銷網(wǎng)站建設(shè)服務(wù),以良好的商業(yè)信譽(yù),完善的服務(wù)及深厚的技術(shù)力量處于同行領(lǐng)先地位。

Android是什么

Android是一種基于Linux內(nèi)核的自由及開放源代碼的操作系統(tǒng),主要使用于移動(dòng)設(shè)備,如智能手機(jī)和平板電腦,由美國Google公司和開放手機(jī)聯(lián)盟領(lǐng)導(dǎo)及開發(fā)。

在進(jìn)行Android應(yīng)用開發(fā)過程中,有時(shí)候會(huì)遇到獲取當(dāng)前Android設(shè)備所使用的網(wǎng)絡(luò)IP地址的場景,有時(shí)候需要本地的網(wǎng)絡(luò)IP地址,即局域網(wǎng)地址,更多的時(shí)候是需要當(dāng)前網(wǎng)絡(luò)的真實(shí)的對(duì)外IP地址,即真實(shí)的網(wǎng)絡(luò)地址,如大數(shù)據(jù)分析時(shí)往往需要Android設(shè)備上傳本地的外網(wǎng)地址。本文對(duì)各種IP地址的獲取進(jìn)行了總結(jié)。

首先用大家比較熟悉的電腦端局域網(wǎng)地址和外網(wǎng)地址的獲取方式對(duì)比一下:(1)、電腦端局域網(wǎng)地址獲取方式,可以通過在終端命令行輸入ipconfig進(jìn)行查看,如下圖IPv地址標(biāo)識(shí)的就是本機(jī)的局域網(wǎng)地址:

Android開發(fā)如何獲取手機(jī)內(nèi)網(wǎng)IP地址與外網(wǎng)IP地址

(2)、電腦端外網(wǎng)地址的獲取方式,可以通過在瀏覽器里面查詢,如在百度頁面搜索“IP地址查詢”查看本地外網(wǎng)地址,如下圖是筆者本機(jī)的外網(wǎng)地址:

Android開發(fā)如何獲取手機(jī)內(nèi)網(wǎng)IP地址與外網(wǎng)IP地址

本地IP地址有兩種情況:一是wifi下,二是移動(dòng)網(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 "";
  }

移動(dòng)網(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)地址非移動(dòng)網(wǎng)絡(luò)

獲取Android設(shè)備的外網(wǎng)地址,即當(dāng)前Wifi網(wǎng)絡(luò)真正的網(wǎng)絡(luò)地址,也即是網(wǎng)絡(luò)運(yùn)營商分配給用戶的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地址時(shí)出現(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 "";
  }

下面在為大家提供兩個(gè)獲取手機(jī)IP地址的實(shí)例源碼

獲取內(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;
	}

關(guān)于“Android開發(fā)如何獲取手機(jī)內(nèi)網(wǎng)IP地址與外網(wǎng)IP地址”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

網(wǎng)站欄目:Android開發(fā)如何獲取手機(jī)內(nèi)網(wǎng)IP地址與外網(wǎng)IP地址
當(dāng)前路徑:http://muchs.cn/article12/isjcdc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站收錄、小程序開發(fā)外貿(mào)建站、標(biāo)簽優(yōu)化Google、網(wǎng)站設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)