rocketmq中的代码

  1. public static byte[] getIP() {
  2. try {
  3. Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
  4. InetAddress ip = null;
  5. byte[] internalIP = null;
  6. while (allNetInterfaces.hasMoreElements()) {
  7. NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
  8. Enumeration addresses = netInterface.getInetAddresses();
  9. while (addresses.hasMoreElements()) {
  10. ip = (InetAddress) addresses.nextElement();
  11. if (ip != null && ip instanceof Inet4Address) {
  12. byte[] ipByte = ip.getAddress();
  13. if (ipByte.length == 4) {
  14. if (ipCheck(ipByte)) {
  15. if (!isInternalIP(ipByte)) {
  16. return ipByte;
  17. } else if (internalIP == null) {
  18. internalIP = ipByte;
  19. }
  20. }
  21. }
  22. } else if (ip != null && ip instanceof Inet6Address) {
  23. byte[] ipByte = ip.getAddress();
  24. if (ipByte.length == 16) {
  25. if (ipV6Check(ipByte)) {
  26. if (!isInternalV6IP(ip)) {
  27. return ipByte;
  28. }
  29. }
  30. }
  31. }
  32. }
  33. }
  34. if (internalIP != null) {
  35. return internalIP;
  36. } else {
  37. throw new RuntimeException("Can not get local ip");
  38. }
  39. } catch (Exception e) {
  40. throw new RuntimeException("Can not get local ip", e);
  41. }
  42. }

apollo代码

  1. private void load() {
  2. String ip = getProperty("host.ip");
  3. if (ip != null) {
  4. try {
  5. m_local = InetAddress.getByName(ip);
  6. return;
  7. } catch (Exception e) {
  8. System.err.println(e);
  9. // ignore
  10. }
  11. }
  12. try {
  13. Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
  14. List<NetworkInterface> nis = interfaces == null ? Collections.<NetworkInterface>emptyList() : Collections.list(interfaces);
  15. List<InetAddress> addresses = new ArrayList<InetAddress>();
  16. InetAddress local = null;
  17. try {
  18. for (NetworkInterface ni : nis) {
  19. if (ni.isUp() && !ni.isLoopback()) {
  20. addresses.addAll(Collections.list(ni.getInetAddresses()));
  21. }
  22. }
  23. local = findValidateIp(addresses);
  24. } catch (Exception e) {
  25. // ignore
  26. }
  27. if (local != null) {
  28. m_local = local;
  29. return;
  30. }
  31. } catch (SocketException e) {
  32. // ignore it
  33. }
  34. m_local = InetAddress.getLoopbackAddress();
  35. }