开发者

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

I need to print all the mac addresses of my machine. The recommended way is to use NetworkInterface.getNetworkInterfaces() and iterate on the enumeration returned. However when some devices are down ( NO Ip is configured ) then the above method will not return the interfaces.

Running "ip addr" will return the following

  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 scope host lo inet6 ::1/128 scope host valid_lft forever preferred_lft forever
  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 scope link valid_lft forever preferred_lft forever
  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

However when I run Java code (even as root or with network privileges) I only get the loopback and G1 interfaces.

Here is the code I wrote for testing purposes :

Enumeration<NetworkInterface> ni = NetworkInterface.getNetworkInterfaces();
while(ni.hasMoreElem开发者_高级运维ents()){
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());
}
}

The output is: 00:03:B2:75:99:C3 (of G1) only.

I do want a pure java solution if possible.

Any thoughts ?


Looks like the "ip addr" shows all network adapters, but not all are configured with an internet address. So, the Java returns only network interfaces, i.e. configured adapters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜