Created
August 9, 2017 17:42
-
-
Save gilday/493551ee03ceb2c4aaa688f5a6e53c5a to your computer and use it in GitHub Desktop.
java retrieve a mac address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* get local mac address as a string. useful for scheduling tasks to happen at the same time every day on a given machine, but at different times across all machines | |
*/ | |
static String mac() { | |
final ArrayList<NetworkInterface> ifaces; | |
try { | |
ifaces = Collections.list(NetworkInterface.getNetworkInterfaces()); | |
// sort the interfaces by name so we consistently pick the same interface | |
Collections.sort(ifaces, new Comparator<NetworkInterface>() { | |
@Override | |
public int compare(final NetworkInterface o1, final NetworkInterface o2) { | |
return o1.getName().compareTo(o2.getName()); | |
} | |
}); | |
} catch (SocketException e) { | |
throw new ContrastException("unable to find network interfaces", e); | |
} | |
String mac = null; | |
for (NetworkInterface iface : ifaces) { | |
final byte[] addr; | |
try { | |
addr = iface.getHardwareAddress(); | |
} catch (SocketException e) { | |
continue; | |
} | |
if (addr == null || addr.length == 0) { | |
continue; | |
} | |
// TODO:JAVA8 map + join | |
final StringBuilder builder = new StringBuilder(); | |
for (final byte macByte : addr) { | |
final String hex = String.format("%02X", macByte); | |
builder.append(hex); | |
} | |
mac = builder.toString(); | |
break; | |
} | |
if (mac == null) { | |
throw new ContrastException("unable to find network interface with a mac address"); | |
} | |
return mac; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment