1. 程式人生 > >android ip獲取(已經上線使用3年)

android ip獲取(已經上線使用3年)


    /**
     * 當前ip地址
     *
     * @return String ip
     */
    private static String getIpAddress() {
        try {
            WifiManager wifiManager = (WifiManager) MyApplication.getAppContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            assert wifiManager != null;
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            return defaultIp((ipAddress & 0xFF) + "." +
                    ((ipAddress >> 8) & 0xFF) + "." +
                    ((ipAddress >> 16) & 0xFF) + "." +
                    (ipAddress >> 24 & 0xFF));
        } catch (Exception ignored) {

        }
        return defaultIp("");
    }

    private static String defaultIp(String ip) {
        if ("".equals(ip) || ip == null) {
            return "0.0.0.0";
        } else {
            return ip;
        }
    }