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

自闭症网瘾萝莉.ら 提交于 2019-12-04 22:48:34

工作需要获取到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);
    }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!