在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 }