Android-工作遭遇-获取ip地址

工作需要获取到ip地址


    public static String getIPAddress(Context context) {
        try {
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (null != connMgr) {
                NetworkInfo info = connMgr.getActiveNetworkInfo();
                if ((null != info) && (info.isAvailable())) {
                    if (1 == info.getType()) {
                        return getIPAddrOnWIFI(context);
                    }
                    return getIPAddrOnMobile();
                }
            }
        } catch (Throwable t) {
            LOG.e("SystemUtils", "get IP failed(" + t.getClass().getSimpleName() + "): " + t
                    .getMessage());
        }
        return "";
    }

    private static String getIPAddrOnMobile()
            throws SocketException {
        Enumeration<NetworkInterface> elements = NetworkInterface.getNetworkInterfaces();
        while (elements.hasMoreElements()) {
            NetworkInterface         element = (NetworkInterface) elements.nextElement();
            Enumeration<InetAddress> addrs   = element.getInetAddresses();
            if (null != addrs) {
                while (addrs.hasMoreElements()) {
                    InetAddress addr = (InetAddress) addrs.nextElement();
                    if ((null != addr) && (!addr.isLoopbackAddress()) && ((addr instanceof Inet4Address))) {
                        return addr.getHostAddress();
                    }
                }
            }
        }
        return "";
    }

    private static String getIPAddrOnWIFI(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo    wifiInfo    = wifiManager.getConnectionInfo();
        return ip2s(wifiInfo.getIpAddress());
    }

    private static String ip2s(int i) {
        return (i & 0xFF) + "." + (i >> 8 & 0xFF) + "." + (i >> 16 & 0xFF) + "." + (i >> 24 & 0xFF);
    }

猜你喜欢

转载自blog.csdn.net/ci250454344/article/details/82801243
今日推荐