获取公网IP和局域网IP

获取公网IP和局域网IP

获取公网IP需要进行网络请求,所以我这里使用线程进行访问,不然在主线程去修改UI会报错

公网IP:

private Handler handler =null;//先定义一个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("公网IP:" + ipLine);
        }
    };

局域网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) {//当前使用2G/3G/4G网络
                        try {
                              //Enumeration en=NetworkInterface.getNetworkInterfaces();
                              for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                                    NetworkInterface intf = en.nextElement();
                                    for (Enumeration 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) {//当前使用无线网络
                        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                        String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                        return ipAddress;
                  }
            } else {
                  //当前无网络连接,请在设置中打开网络
            }
            return null;
      }

实测有效,小米获取公网IP还有点问题,华为没问题

喜欢的点一个关注吧,后续会更新这个

你可能感兴趣的:(获取公网IP和局域网IP)