Android获取外网和内网ip地址

前言:

最近有个需求需要获取外网ip地址,找了很多资料都不行,要么是报错,于是自己整理了一下方法:

1.获取内网ip地址:

/**
 * 获取内网ip地址
 * @param context
 * @return
 */
public static String getIntranetIPAddress(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 {
                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) {//当前使用无线网络
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
            return ipAddress;
        }
    } else {
        //当前无网络连接,请在设置中打开网络
    }
    return null;
}
​
/**
 * 将得到的int类型的IP转换为String类型
 *
 * @param ip
 * @return
 */
public static String intIP2StringIP(int ip) {
    return (ip & 0xFF) + "." +
            ((ip >> 8) & 0xFF) + "." +
            ((ip >> 16) & 0xFF) + "." +
            (ip >> 24 & 0xFF);
}

2.测试代码如下:

img

3.打印日志为:

img

4.获取外网IP地址方法:

/**
 * 获取外网的IP(要访问Url,要放到后台线程里处理)
 *
 * @param @return
 * @return String
 * @throws
 * @Title: GetNetIp
 * @Description:
 */
public static String getNetExtraNetIpAddress() {
    URL infoUrl;
    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 sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null){
                sb.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(sb.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();
        }
    }
    LogUtils.e("getNetIp", ipLine);
    return ipLine;
}

5.测试代码为:

img

6.打印日志为:61.49.113.194

img

7.测试了华为、小米手机,模拟器也测试了几款都能正常获取内外网IP地址,TV和盒子也能正常获取.

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值