Explorar o código

Network 中遍历指定名字前缀的 Linux 网卡接口

reghao hai 10 meses
pai
achega
fea0eefad1

+ 19 - 17
common/src/main/java/cn/reghao/devops/common/machine/Network.java

@@ -24,28 +24,30 @@ public class Network implements MachineData<List<NetworkDetail>, NetworkStat> {
                 NetworkInterface iface = interfaces.nextElement();
                 String ifaceName = iface.getName();
                 // 过滤掉 localhost 和虚拟网卡
-                if (ifaceName.startsWith("lo") || ifaceName.startsWith("docker")
-                        || ifaceName.startsWith("v") || ifaceName.startsWith("br")) {
-                    continue;
-                }
-                String ifaceMac = macAddr(iface.getHardwareAddress());
-                NetworkDetail networkDetail = new NetworkDetail(ifaceName, ifaceMac);
+                if (ifaceName.startsWith("enp")
+                        || ifaceName.startsWith("wlp")
+                        || ifaceName.startsWith("eth")
+                        || ifaceName.startsWith("wlan")
+                        || ifaceName.startsWith("em")) {
+                    String ifaceMac = macAddr(iface.getHardwareAddress());
+                    NetworkDetail networkDetail = new NetworkDetail(ifaceName, ifaceMac);
 
-                Enumeration<InetAddress> inetAddrs = iface.getInetAddresses();
-                while (inetAddrs.hasMoreElements()) {
-                    InetAddress address = inetAddrs.nextElement();
-                    if (!address.isLoopbackAddress()) {
-                        if (address instanceof Inet4Address) {
-                            networkDetail.setIpv4(address.getHostAddress());
-                        } else if (address instanceof Inet6Address) {
-                            networkDetail.setIpv6(address.getHostAddress());
+                    Enumeration<InetAddress> inetAddrs = iface.getInetAddresses();
+                    while (inetAddrs.hasMoreElements()) {
+                        InetAddress address = inetAddrs.nextElement();
+                        if (!address.isLoopbackAddress()) {
+                            if (address instanceof Inet4Address) {
+                                networkDetail.setIpv4(address.getHostAddress());
+                            } else if (address instanceof Inet6Address) {
+                                networkDetail.setIpv6(address.getHostAddress());
+                            }
                         }
                     }
-                }
 
-                list.add(networkDetail);
+                    list.add(networkDetail);
+                }
             }
-        } catch (SocketException e) {
+        } catch (Exception e) {
             e.printStackTrace();
         }
         return list;