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;
    }


    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

更多相关文章

  1. android 判断是否有可用网络
  2. android文件下载
  3. android录音和得到音量
  4. android 检测是否有网络连接
  5. android 启动第三方APP的方式
  6. Android判断当前的Activity
  7. 检测Android设备有线网络连接状态
  8. Android(安卓)Wifi的使用
  9. android中定制的dialog

随机推荐

  1. android 蓝牙连接通信
  2. Android(安卓)Support Library的前世今生
  3. Unity调用Android(安卓)jar包方法——(三
  4. Android之HAL粗解
  5. Android读取联系人的姓名及电话号码
  6. Android竖屏模式实现横屏效果
  7. Android项目架构 - 主页导航
  8. 网易考拉 Android(安卓)通知栏适配全方案
  9. Android内核开发:系统启动速度优化
  10. Android(安卓)消息推送:第三方消息推送平