Java获取本地IP(Linux和windows)
在Linux系统和windows系统使用java获取本地IP的方法是不同的,这就导致了生产环境与实际运用环境不同而导致代码出错。
1 package com.cfcc.cfcs.common.utils; 2 3 import java.net.InetAddress; 4 import java.net.NetworkInterface; 5 import java.util.Enumeration; 6 7 public class IPUtils { 8 /** 9 * 获取本地IP地址 10 * 11 * @throws Exception 12 */ 13 public static String getLocalIP() throws Exception { 14 if (isWindowsOS()) { 15 return InetAddress.getLocalHost().getHostAddress(); 16 } else { 17 return getLinuxLocalIp(); 18 } 19 } 20 21 /** 22 * 获取Linux下的IP地址 23 * 24 * @return IP地址 25 * @throws Exception 26 */ 27 private static String getLinuxLocalIp() throws Exception { 28 String ip = ""; 29 try { 30 for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { 31 NetworkInterface intf = en.nextElement(); 32 String name = intf.getName(); 33 if (!name.contains("docker") && !name.contains("lo")) { 34 for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { 35 InetAddress inetAddress = enumIpAddr.nextElement(); 36 if (!inetAddress.isLoopbackAddress()) { 37 String ipaddress = inetAddress.getHostAddress().toString(); 38 if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) { 39 ip = ipaddress; 40 // System.out.println(ipaddress); 41 } 42 } 43 } 44 } 45 } 46 } catch (Exception ex) { 47 ex.printStackTrace(); 48 } 49 return ip; 50 } 51 52 /** 53 * 判断操作系统是否是Windows 54 * 55 * @return 56 */ 57 public static boolean isWindowsOS() { 58 boolean isWindowsOS = false; 59 String osName = System.getProperty("os.name"); 60 if (osName.toLowerCase().indexOf("windows") > -1) { 61 isWindowsOS = true; 62 } 63 return isWindowsOS; 64 } 65 66 public static void main(String[] args) throws Exception { 67 System.out.println(getLocalIP()); 68 } 69 }
分类:
java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!