獲取公網(wǎng)IP和局域網(wǎng)IP

獲取公網(wǎng)IP和局域網(wǎng)IP

獲取公網(wǎng)IP需要進(jìn)行網(wǎng)絡(luò)請(qǐng)求,所以我這里使用線程進(jìn)行訪問(wèn),不然在主線程去修改UI會(huì)報(bào)錯(cuò)

公網(wǎng)IP:

private Handler handler =null;//先定義一個(gè)Handler


handler =new Handler();

new Thread(new Runnable(){

@Override

    public void run() {

handler.post(runnableUi);

    }

}).start();


Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            URL infoUrl = null;
            InputStream inStream = null;
            String ipLine = "";
            HttpURLConnection httpConnection = null;
            try {
                infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
                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();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            String aaaa=ipLine;
            gw.setText("公網(wǎng)IP:" + ipLine);
        }
    };

局域網(wǎng)IP

public static String getIPAddress(Context context) {
            NetworkInfo info = ((ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                  if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//當(dāng)前使用2G/3G/4G網(wǎng)絡(luò)
                        try {
                              //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                              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 (SocketException e) {
                              e.printStackTrace();
                        }


                  } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//當(dāng)前使用無(wú)線網(wǎng)絡(luò)
                        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                        String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                        return ipAddress;
                  }
            } else {
                  //當(dāng)前無(wú)網(wǎng)絡(luò)連接,請(qǐng)?jiān)谠O(shè)置中打開(kāi)網(wǎng)絡(luò)
            }
            return null;
      }

實(shí)測(cè)有效,小米獲取公網(wǎng)IP還有點(diǎn)問(wèn)題,華為沒(méi)問(wèn)題

喜歡的點(diǎn)一個(gè)關(guān)注吧,后續(xù)會(huì)更新這個(gè)簡(jiǎn)書(shū)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、簡(jiǎn)歷準(zhǔn)備 1、個(gè)人技能 (1)自定義控件、UI設(shè)計(jì)、常用動(dòng)畫(huà)特效 自定義控件 ①為什么要自定義控件? Andr...
    lucas777閱讀 5,389評(píng)論 2 54
  • 引言 我先拋出一個(gè)簡(jiǎn)單的問(wèn)題。 我所在的公司啟用的是獨(dú)立IP地址,公司下的所有電腦都在一個(gè)局域網(wǎng)內(nèi),然從每臺(tái)計(jì)算機(jī)...
    OzanShareing閱讀 5,438評(píng)論 2 23
  • 作者si1ence2016.05.20 10:24* http://www.itdecent.cn/p/bc3f8...
    Kiddz閱讀 1,269評(píng)論 0 12
  • 我不是怕狗 我只是害怕一切有攻擊性的東西 這幾天在家呆的實(shí)在無(wú)聊,剛好表姐回來(lái)了,便想著去找她玩,我小時(shí)候被雞...
    蘇子應(yīng)閱讀 522評(píng)論 2 2
  • 文/鄧琪 前些日子帶上了紅泥小火爐和茶具到寺廟山中去遠(yuǎn)足,取了清冽的泉水燒開(kāi)沏茶淺酌,禪音緲緲,山頂?shù)暮珊?,?..
    晴滿閱讀 351評(píng)論 0 2

友情鏈接更多精彩內(nèi)容