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

Android 獲取外網與內網 IP 的兩種方法

編輯:關於 Android 程式設計

不廢話,直接上程式碼。獲取 IP 通常分兩種需求:一個是裝置在公網上的出口 IP(外網 IP),一個是裝置在區域網路中的 IP(內網 IP)。

先看外網 IP。思路是訪問一個會回顯 IP 的網址,再用正則表達式把 IP 從返回的頁面中抓出來。注意這個操作涉及網路請求,一定要放到後台線程裡執行:

/**
 * 獲取外網的 IP(要訪問 Url,需放到後台線程裡處理)
 * @return 外網 IP 字串
 */
public static String GetNetIp() {
    URL infoUrl = null;
    InputStream inStream = null;
    String ipLine = "";
    HttpURLConnection httpConnection = null;
    try {
        infoUrl = new URL("https://ip168.com/");
        URLConnection connection = infoUrl.openConnection();
        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();
            String line = null;
            while ((line = reader.readLine()) != null) {
                strber.append(line + "\n");
            }
            Pattern pattern = Pattern.compile(
                "((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))");
            Matcher matcher = pattern.matcher(strber.toString());
            if (matcher.find()) {
                ipLine = matcher.group();
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            inStream.close();
            httpConnection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return ipLine;
}

再看內網 IP。這就單純多了,只需遍歷所有網路介面,找出第一個非 loopback 的 IPv4 位址即可:

/**
 * 獲取本地 IP
 * @return 內網 IP 字串
 */
public static String getLocalIpAddress() {
    try {
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface ni = en.nextElement();
            Enumeration<InetAddress> enIp = ni.getInetAddresses();
            while (enIp.hasMoreElements()) {
                InetAddress inet = enIp.nextElement();
                if (!inet.isLoopbackAddress() && (inet instanceof Inet4Address)) {
                    return inet.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return "0";
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved