IpUtil.java 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package com.xxl.job.client.util;
  2. import java.net.InetAddress;
  3. import java.net.NetworkInterface;
  4. import java.net.UnknownHostException;
  5. import java.util.Enumeration;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. /**
  9. * get ip
  10. * @author xuxueli 2016-5-22 11:38:05
  11. */
  12. public class IpUtil {
  13. private static final Logger logger = LoggerFactory.getLogger(IpUtil.class);
  14. /**
  15. * 获取本机ip
  16. * @return
  17. */
  18. public static String getIp() {
  19. try {
  20. Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
  21. InetAddress address = null;
  22. while (interfaces.hasMoreElements()) {
  23. NetworkInterface ni = interfaces.nextElement();
  24. Enumeration<InetAddress> addresses = ni.getInetAddresses();
  25. while (addresses.hasMoreElements()) {
  26. address = addresses.nextElement();
  27. if (!address.isLoopbackAddress() && address.getHostAddress().indexOf(":") == -1) {
  28. return address.getHostAddress();
  29. }
  30. }
  31. }
  32. logger.info("xxl job getHostAddress fail");
  33. return null;
  34. } catch (Throwable t) {
  35. logger.error("xxl job getHostAddress error, {}", t);
  36. return null;
  37. }
  38. }
  39. public static void main(String[] args) throws UnknownHostException {
  40. System.out.println(InetAddress.getLocalHost().getCanonicalHostName());
  41. System.out.println(InetAddress.getLocalHost().getHostName());
  42. System.out.println(getIp());
  43. }
  44. }