Skip to content

Commit 914a4c2

Browse files
committed
fix #32
1 parent 84af249 commit 914a4c2

File tree

1 file changed

+42
-10
lines changed

1 file changed

+42
-10
lines changed

index.js

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,12 @@ lib.getMacAddress = require("./lib/getmacaddress.js");
88
lib.getAllInterfaces = require("./lib/getallinterfaces.js");
99
lib.networkInterfaces = require("./lib/networkinterfaces.js");
1010

11+
// devices like en0 (mac), eth3 (linux), Ethernet (windows), etc. are preferred
12+
var goodIfaces = new RegExp("^((en|eth)[0-9]+|ethernet)$", "i");
13+
14+
// https://github.com/scravy/node-macaddress/issues/32
15+
var badIfaces = new RegExp("^(vboxnet[0-9]+)$", "i");
16+
1117
lib.one = function () {
1218
// one() can be invoked in several ways:
1319
// one() -> Promise<string>
@@ -41,21 +47,47 @@ lib.one = function () {
4147
var addresses = {};
4248
var best = [];
4349
var args = [];
44-
Object.keys(ifaces).forEach(function (d) {
45-
args.push(d);
46-
if (typeof ifaces[d].mac === "string" && ifaces[d].mac !== "00:00:00:00:00:00") {
47-
addresses[d] = ifaces[d].mac;
48-
if (ifaces[d].ipv4 || ifaces[d].ipv6) {
49-
if (ifaces[d].ipv4 && ifaces[d].ipv6) {
50-
best.unshift(addresses[d]);
51-
} else {
52-
best.push(addresses[d]);
50+
Object.keys(ifaces).forEach(function (name) {
51+
args.push(name);
52+
var score = 0;
53+
var iface = ifaces[name];
54+
if (typeof iface.mac === "string" && iface.mac !== "00:00:00:00:00:00") {
55+
addresses[name] = iface.mac;
56+
if (iface.ipv4 || iface.ipv6) {
57+
score += 1;
58+
if (iface.ipv4 && iface.ipv6) {
59+
score += 1;
5360
}
5461
}
62+
if (goodIfaces.test(name)) {
63+
score += 2;
64+
}
65+
if (badIfaces.test(name)) {
66+
score -= 3;
67+
}
68+
best.push({
69+
name: name,
70+
score: score,
71+
mac: iface.mac
72+
});
5573
}
5674
});
5775
if (best.length > 0) {
58-
util.nextTick(callback.bind(null, null, best[0]));
76+
best.sort(function (left, right) {
77+
// the following will sort items with a higher score to the beginning
78+
var comparison = right.score - left.score;
79+
if (comparison !== 0) {
80+
return comparison;
81+
}
82+
if (left.name < right.name) {
83+
return -1;
84+
}
85+
if (left.name > right.name) {
86+
return 1;
87+
}
88+
return 0;
89+
});
90+
util.nextTick(callback.bind(null, null, best[0].mac));
5991
return;
6092
}
6193
args.push(lib.getAllInterfaces);

0 commit comments

Comments
 (0)