rocketmq中的代码
public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } else if (ip != null && ip instanceof Inet6Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 16) { if (ipV6Check(ipByte)) { if (!isInternalV6IP(ip)) { return ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); }}
apollo代码
private void load() { String ip = getProperty("host.ip"); if (ip != null) { try { m_local = InetAddress.getByName(ip); return; } catch (Exception e) { System.err.println(e); // ignore } } try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); List<NetworkInterface> nis = interfaces == null ? Collections.<NetworkInterface>emptyList() : Collections.list(interfaces); List<InetAddress> addresses = new ArrayList<InetAddress>(); InetAddress local = null; try { for (NetworkInterface ni : nis) { if (ni.isUp() && !ni.isLoopback()) { addresses.addAll(Collections.list(ni.getInetAddresses())); } } local = findValidateIp(addresses); } catch (Exception e) { // ignore } if (local != null) { m_local = local; return; } } catch (SocketException e) { // ignore it } m_local = InetAddress.getLoopbackAddress(); }