Android获取IP地址的第一种方法(判断的地方有瑕疵),代码:
上面这种方法没有明确的把Ip地址按类区分开,下面这种方式是优化后的版本,可以封装成一个工具类,详细代码如下:final List<String> uris = new ArrayList<>(); InetAddress ip = null; Enumeration<NetworkInterface> netInterfaces = null; try { netInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { e.printStackTrace(); } while (netInterfaces.hasMoreElements()) { NetworkInterface ni = netInterfaces.nextElement(); // 遍历所有ip Enumeration<InetAddress> ips = ni.getInetAddresses(); while (ips.hasMoreElements()) { //我的需求是匹配10.42.0.1的地址 ip = ips.nextElement(); String fip = ip.getHostAddress(); if (fip.trim().length() >= 7) { if (fip.trim().substring(0, 7).equals("10.42.0")) { uris.add(fip); if (uris.size() > 0) { try { this.setCustomMaterUri(new URI("http://10.42.0.1:11311/")); } catch (URISyntaxException e) { e.printStackTrace(); } } else { Toast.makeText(this, "IP地址错误", Toast.LENGTH_SHORT).show(); } } } } }
public class Util { public static final String ACRA_REPORT_ADDRESS = "http://developer.miivii.com:5984/acra-bugreport/_design/acra-storage/_update/report"; public static final String ACRA_REPORT_LOGIN = "bugreport"; public static final String ACRA_REPORT_PASSWORD = "miiviibugreport"; // instead by your own machine IP address which you will connect to. public static final String ROS_MASTER_URI = "http://192.168.31.213:11311/"; public static String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); if(!intf.getDisplayName().equals("eth0")) continue; for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e("WifiPreference IpAddress", ex.toString()); } return null; } public static boolean configDevice(){ String ip = getLocalIpAddress(); Log.e("========","======ip==="+ip); if(ip == null) return false; if(ip.substring(0,8).equals("10.42.0.")) return true; return false; } public static URI getCustomURI() { URI customMasterUri = null; try { customMasterUri = new URI("http://10.42.0.1:11311/"); } catch (URISyntaxException e) { throw new RosRuntimeException(e); } return customMasterUri; } }
相信会有用。