Android 获取外网IP,实测有效

Posted 飞剑的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 获取外网IP,实测有效相关的知识,希望对你有一定的参考价值。

网上有很多获取IP的例子,不过都是获取到的本地ip,还有的是因为走不通了,获取到的ip为空,下面看实测获取到外网IP的代码,注意需要在线程里面执行

 

/**
     * 获取外网的IP(要访问Url,要放到后台线程里处理)
     *
     * @param @return
     * @return String
     * @throws
     * @Title: GetNetIp
     * @Description:
     */
    public static String getNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        String ipLine = "";
        HttpURLConnection httpConnection = null;
        try {
//            infoUrl = new URL("http://ip168.com/");
            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();
            }
        }
        Log.e("getNetIp", ipLine);
        return ipLine;
    }

 

以上是关于Android 获取外网IP,实测有效的主要内容,如果未能解决你的问题,请参考以下文章

android 获取IP地址

android 获取IP地址

android 获取IP地址

Java 获取IP工具类Vo类整理记录

Java 获取IP工具类Vo类整理记录

通过url获取当前外网ip