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 }
复制代码

 

posted @   莴苣&  阅读(359)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示