美文网首页IT技术
安卓手机获取IP地址

安卓手机获取IP地址

作者: 人丑茶凉 | 来源:发表于2019-03-27 18:17 被阅读39次

    安卓手机获取IP地址有两种方法:

    • 一、请求获取IP地址的接口

    许多获取IP地址的网站都有这个功能,例如我项目中用到过的接口 http://pv.sohu.com/cityjson?ie=utf-8

    然后通过解析返回值 result 即可获得IP地址。

    int start = result.indexOf("{");
    int end = result.indexOf("}");
    String json = result.substring(start, end + 1);
    if(json != null) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            String phoneIp = "";
            phoneIp  = jsonObject.optString("cip");
    
            Log.d("---本机ip为---" + phoneIp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    • 二、通过分别获取GPRS和无线网环境下的IP (推荐)

    此种方法不依赖任何三方服务,亲测有效,比较可靠,代码如下。

    public class IpUtils {
        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 {
                        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);
        }
    }
    

    相关文章

      网友评论

        本文标题:安卓手机获取IP地址

        本文链接:https://www.haomeiwen.com/subject/lxjtbqtx.html