5
votes

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.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());
}
}

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

I do want a pure java solution if possible.
Any thoughts ?

1

1 Answers

1
votes

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.