获取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");
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述