Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 取得 WiFi 外網 IP 的兩種做法

編輯:關於 Android 程式設計

先釐清一個常見誤解

很多人搜尋「取得 WiFi IP」時,真正想拿的其實是兩種完全不同的東西。一種是裝置在區網中的私有 IP,透過 WifiManager.getConnectionInfo().getIpAddress() 就能取得,完全不需要網路;另一種是對外那個公開 IP,則必須發請求問外部服務。

以下說明的是後者。

做法一:抓取回傳頁面並擷取字串

public static String GetNetIp() {
    URL infoUrl = null;
    InputStream inStream = null;
    try {
        infoUrl = new URL("https://ip38.com");
        URLConnection connection = infoUrl.openConnection();
        HttpURLConnection httpConnection = (HttpURLConnection) connection;

        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inStream = httpConnection.getInputStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                strber.append(line + "\n");
            }
            inStream.close();
            // 從回傳內容中擷取 IP 字串
            line = strber.substring(378, 395);
            return line.replaceAll(" ", "");
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

這個寫法能動,但很脆弱。用固定的字元索引 substring(378, 395) 去切字串,等於把對方網頁的排版寫死在程式碼裡——對方改一次版面,你的功能就壞了,而且壞得毫無徵兆。只適合臨時應急。

做法二:使用回傳 JSON 的服務

比較可靠的方式是找一個提供結構化資料的服務,例如淘宝的 IP 查詢介面:

public static String GetNetIp() {
    String IP = "";
    try {
        String address = "https://ip.taobao.com/service/getIpInfo2.php?ip=myip";
        URL url = new URL(address);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);

        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");
            if (code.equals("0")) {
                JSONObject data = jsonObject.getJSONObject("data");
                IP = data.getString("ip")
                   + "(" + data.getString("country") + data.getString("area") + "區 "
                   + data.getString("region") + data.getString("city")
                   + data.getString("isp") + ")";
                Log.e("提示", "您的 IP 位址是:" + IP);
            } else {
                Log.e("提示", "IP 介面異常,無法取得 IP 位址!");
            }
        } else {
            Log.e("提示", "網路連線異常,無法取得 IP 位址!");
        }
    } catch (Exception e) {
        Log.e("提示", "取得 IP 位址時出現異常,資訊是:" + e.toString());
    }
    return IP;
}

相較之下,這種做法有幾個明顯優勢:解析的是結構化欄位而非字元位置,介面改版時只要欄位名稱不變就不受影響;同時還能拿到國家、地區、城市與 ISP 等額外資訊;每個失敗分支都有明確的錯誤訊息,排查問題時不必猜。

幾點實務提醒

這個操作必須放在主執行緒以外,NetworkOnMainThreadException 是必然的結果。此外記得在 manifest 加上 android.permission.INTERNET。

還有一點值得思考:取得「外網 IP」只能知道出口位址,如果使用者同時開著 VPN 或代理,拿到的就不是真實網路的位址了。若需求其實是區網 IP,請改用 WifiManager,那樣既快又不需要任何權限以外的網路連線。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved