Android获取当前设备有效的IP地址

来源:互联网 发布:小甲鱼java 百度网盘 编辑:程序博客网 时间:2024/05/31 19:22
获取当前设备有效的IP地址(通过反射来获取)

private InetAddress getActiveAddress() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {        ConnectivityManager connectivityManager = (ConnectivityManager)getContext().getSystemService(Context.CONNECTIVITY_SERVICE);        Method activeLinkPropertiesMethod = connectivityManager.getClass().getDeclaredMethod("getActiveLinkProperties");        activeLinkPropertiesMethod.setAccessible(true);        Object linkProperties = activeLinkPropertiesMethod.invoke(connectivityManager);        if (linkProperties == null) return null;        Method addressesMethod = linkProperties.getClass().getDeclaredMethod("getAddresses");        Collection<InetAddress> inetAddresses = (Collection<InetAddress>)addressesMethod.invoke(linkProperties);        Iterator<InetAddress> iterator = inetAddresses.iterator();        return iterator.hasNext() ? iterator.next() : null;    }




0 0
原创粉丝点击