Android 5.1获取IP

来源:互联网 发布:淘宝30天最低价 编辑:程序博客网 时间:2024/05/16 12:20
在Android 5.1的系统,获取IP地址,试了好几个方法都无法得到正确的和系统设置中一致的IP,最后发现下面这个是唯一可以使用的,其他有几个要么是乱码要么和系统设置里的不一致。
public static String getLocalIpAddress() {String ip="";try {for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {NetworkInterface intf = en.nextElement();if (intf.getName().equals("usbnet0")) {continue;}for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {InetAddress inetAddress = enumIpAddr.nextElement();if (!inetAddress.isLoopbackAddress()&& (inetAddress instanceof Inet4Address)) {ip=inetAddress.getHostAddress();}}}} catch (SocketException ex) {Log.e(TAG, ex.toString());}return ip;}
原创粉丝点击