簡體   English   中英

無法在Linux上獲得NetworkInterface.getNetworkInterfaces的所有網絡接口

[英]Unable to get all network interfaces with NetworkInterface.getNetworkInterfaces on Linux

我需要打印機器的所有mac地址。 建議的方法是使用NetworkInterface.getNetworkInterfaces()並迭代返回的枚舉。 但是,當某些設備關閉時(NO Ip已配置),則上述方法將不會返回接口。

運行“ip addr”將返回以下內容

  1. lo:mtu 16436 qdisc noqueue link / loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8范圍主機lo inet6 :: 1/128范圍主機valid_lft永遠是preferred_lft永遠
  2. G2:mtu 1500 qdisc pfifo_fast qlen 1000 link / ether 00:03:b2:75:99:c2 brd ff:ff:ff:ff:ff:ff
  3. G1:mtu 1500 qdisc pfifo_fast qlen 1000 link / ether 00:03:b2:75:99:c3 brd ff:ff:ff:ff:ff:ff inet 10.205.191.123/16 brd 10.205.255.255 scope global G1 inet6 fe80: :203:b2ff:fe75:99c3 / 64范圍鏈接valid_lft永遠preferred_lft永遠
  4. eth2:mtu 1500 qdisc noop qlen 1000 link / ether 00:03:b2:75:99:c4 brd ff:ff:ff:ff:ff:ff
  5. eth3:mtu 1500 qdisc noop qlen 1000 link / ether 00:03:b2:75:99:c5 brd ff:ff:ff:ff:ff:ff

但是,當我運行Java代碼(即使是root或具有網絡權限)時,我只獲得了環回和G1接口。

這是我為測試目的編寫的代碼:

Enumeration<NetworkInterface> ni = NetworkInterface.getNetworkInterfaces();
while(ni.hasMoreElements()){
NetworkInterface nextElement = ni.nextElement();
byte[] mac = nextElement.getHardwareAddress();
if (mac != null) {
         StringBuffer macAddress = new StringBuffer();
         for (int i = 0; i < mac.length; i++) {
              macAddress.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
         }
         System.out.println(macAddress.toString());
}
}

輸出為: 00:03:B2:75:99:C3 (僅G1)。

如果可能,我確實想要一個純java解決方案。
有什么想法嗎 ?

看起來“ip addr”顯示所有網絡適配器,但並非所有網絡適配器都配置了Internet地址。 因此,Java只返回網絡接口,即配置的適配器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM