Skip to content

Instantly share code, notes, and snippets.

@krzys-h
Created June 14, 2014 14:27
Show Gist options
  • Save krzys-h/4277cc84683ae872a22a to your computer and use it in GitHub Desktop.
Save krzys-h/4277cc84683ae872a22a to your computer and use it in GitHub Desktop.
Java - getting MAC address test program - issue Slowpoke101/FTBLaunch#758
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class TestNetworkInterfaces {
public static void main(String[] args) {
boolean returned = false;
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface network = networkInterfaces.nextElement();
byte[] mac = network.getHardwareAddress();
boolean ok = false;;
if (mac != null && mac.length > 0 && !network.isLoopback() && !network.isVirtual() && !network.isPointToPoint()) {
ok = true;
returned = true;
}
String macStr = "(null)";
if(mac != null && mac.length > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
}
macStr = sb.toString();
}
System.out.println(network.getDisplayName() + " - " + macStr + " - " + network.isLoopback() + " - " + network.isVirtual() + " - " + network.isPointToPoint() + " - " + (ok ? "returned this address" : "doesn't match criteria"));
}
} catch (SocketException e) {
System.out.println("Exception getting MAC address");
System.out.println(e);
}
if(!returned) {
System.out.println("Failed to get MAC address, using defalt logindata key");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment