Just to save the next person from stumbling over the incomplete MAC retrieval code, here is my version that works on my Windows 7 machine as well as other computers. Note that the code may still return different MACs on each invocation in case the user messed with his hardware and the network devices might be returned in different order.
private static final String generateHashIdentifier() throws Exception {
Enumeration<NetworkInterface> networkInterfaces
= NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (networkInterface == null
|| networkInterface.isLoopback()
|| networkInterface.isVirtual()) {
continue;
}
byte[] mac = networkInterface.getHardwareAddress();
if (mac == null || mac.length == 0)
continue;
StringBuilder sb = new StringBuilder();
int zeroFieldCount = 0;
for (int i = 0; i < mac.length; i++) {
if (mac[i] == 0)
zeroFieldCount++;
sb.append(String.format("%02X%s", mac[i],
(i < mac.length - 1) ? "-" : ""));
}
if (zeroFieldCount > 4)
continue;
return sb.toString();
}
throw new RuntimeException("Failed to obtain MAC");
}
In Windows I get tons of additional devices which may or may not return a NULL mac or a mac with mostly zeros. The code tries to find the first device that gives a reasonable MAC and returns it as a nice String as a bonus.