Skip to content

Instantly share code, notes, and snippets.

@tresf
Last active September 27, 2024 15:39
Show Gist options
  • Save tresf/152fbef732f979e43484bda9e37c7d2f to your computer and use it in GitHub Desktop.
Save tresf/152fbef732f979e43484bda9e37c7d2f to your computer and use it in GitHub Desktop.
Find primary MAC Address for a given machine
function findPrimaryMac(adapters, burnedInOnly) {
// Only interested in adapters with MAC addresses
adapters = adapters.filter((adapter) => adapter.mac);
if(burnedInOnly) {
adapters = sift.keep(adapters, {burnedIn: true });
}
// find best match (see https://github.com/qzind/sift/issues/12)
if(adapters.length > 1) {
// First, blindly trust what Java says the primary adapter is
for(var i in adapters) {
if(adapters[i].primary) {
console.debug("Trusting primary adapter as reported by QZ Tray");
return adapters[i];
}
}
console.debug(ipv4s);
// Next, filter adapters without a valid IPv4 value
var ipv4s = adapters.filter((adapter) => adapter.ipv4 && adapter.ipv4 != "127.0.0.1");
if(ipv4s.length == 1) {
console.debug("Assuming primary adapter is the only adapter with a valid IPv4 value");
return ipv4s[0];
}
console.debug(ipv4s);
// Next, filter adapters without "Virtual" in the name
var novirt = ipv4s.filter((adapter) => adapter.interface && adapter.interface.toLowerCase().indexOf("virtual ") === -1);
if(novirt.length == 1) {
console.debug("Assuming primary adapter is the only adapter without 'virtual' in the name");
return novirt[0];
}
console.debug("Trouble finding a primary " + (burnedInOnly ? "" : "non-") + "burned-in MAC address for this machine.");
return null;
}
return adapters[0];
}
var primaryAdapter = findPrimaryMac(adapters, true) || findPrimaryMac(adapters, false);
var primaryMac = primaryAdapter && primaryAdapter.mac;
console.log("Primary MAC is", primaryMac);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment