获取IPV4或IPV6地址
1 public String getPodIp() { 2 try { 3 String ipButton = Application.getProperty("ipButton", "ipv4"); 4 Enumeration < NetworkInterface > networkInterfaces = NetworkInterface.getNetworkInterfaces(); 5 while (networkInterfaces.hasMoreElements()) { 6 Enumeration < InetAddress > inetAddresses = networkInterfaces.nextElement().getInetAddresses(); 7 while (inetAddresses.hasMoreElements()) { 8 InetAddress inetAddress = inetAddresses.nextElement(); 9 if ("ipv4".equals(ipButton)) { 10 if (!inetAddress.isLoopbackAddress() 11 && inetAddress instanceof Inet4Address 12 && !StringUtils.contains(inetAddress.getHostAddress(), ":")) { 13 return inetAddress.getHostAddress(); 14 } 15 } 16 if ("ipv6".equals(ipButton)) { 17 if (!inetAddress.isLoopbackAddress() 18 && !inetAddress.isAnyLocalAddress() 19 && !inetAddress.isLinkLocalAddress() 20 && inetAddress instanceof Inet6Address) { 21 String ip = inetAddress.getHostAddress(); 22 int index = ip.indexOf("%"); 23 if (index > 0) { 24 ip = ip.substring(0, index); 25 } 26 return ip; 27 } 28 } 29 } 30 } 31 } catch (SocketException e) { 32 LOGGER.error("获取IP地址出现异常..:", e); 33 } 34 return ""; 35 }
- 上述代码可在虚机或容器环境下获取主机ip或pod ip
- 根据配置需要获取ipv4或ipv6地址(需要提前知道系统配置的是ipv4或ipv6地址)
如果有获取服务端口需要可通过下面方式获取:(这种方式适用springboot项目。如果是容器环境,要求通过环境变量设置了server.port才能获取的到。)
1 System.getProperty("server.port");