IpUtil.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package net.lab1024.smartadmin.common.heartbeat;
  2. import java.net.InetAddress;
  3. import java.net.NetworkInterface;
  4. import java.util.ArrayList;
  5. import java.util.Enumeration;
  6. import java.util.List;
  7. /**
  8. * @Description: ip工具类
  9. * @Author: sbq
  10. * @CreateDate: 2019/8/8 10:33
  11. * @Version: 1.0
  12. */
  13. public class IpUtil {
  14. /**
  15. * 获得服务器的IP地址
  16. */
  17. public static String getLocalIP() {
  18. String sIP = "";
  19. InetAddress ip = null;
  20. try {
  21. boolean bFindIP = false;
  22. Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
  23. .getNetworkInterfaces();
  24. while (netInterfaces.hasMoreElements()) {
  25. if (bFindIP) {
  26. break;
  27. }
  28. NetworkInterface ni = (NetworkInterface) netInterfaces
  29. .nextElement();
  30. Enumeration<InetAddress> ips = ni.getInetAddresses();
  31. while (ips.hasMoreElements()) {
  32. ip = (InetAddress) ips.nextElement();
  33. if (!ip.isLoopbackAddress()
  34. && ip.getHostAddress().matches(
  35. "(\\d{1,3}\\.){3}\\d{1,3}")) {
  36. bFindIP = true;
  37. break;
  38. }
  39. }
  40. }
  41. } catch (Exception e) {
  42. }
  43. if (null != ip) {
  44. sIP = ip.getHostAddress();
  45. }
  46. return sIP;
  47. }
  48. /**
  49. * @Description: 获得服务器的IP地址(多网卡)
  50. * @Author: sbq
  51. * @CreateDate: 2019/8/8 10:34
  52. * @Version: 1.0
  53. */
  54. public static List<String> getLocalIPS() {
  55. InetAddress ip = null;
  56. List<String> ipList = new ArrayList<String>();
  57. try {
  58. Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
  59. .getNetworkInterfaces();
  60. while (netInterfaces.hasMoreElements()) {
  61. NetworkInterface ni = (NetworkInterface) netInterfaces
  62. .nextElement();
  63. Enumeration<InetAddress> ips = ni.getInetAddresses();
  64. while (ips.hasMoreElements()) {
  65. ip = (InetAddress) ips.nextElement();
  66. if (!ip.isLoopbackAddress()
  67. && ip.getHostAddress().matches(
  68. "(\\d{1,3}\\.){3}\\d{1,3}")) {
  69. ipList.add(ip.getHostAddress());
  70. }
  71. }
  72. }
  73. } catch (Exception e) {
  74. }
  75. return ipList;
  76. }
  77. }