[英]get the mac address of the current machine with node.js using getmac
在 NodeJS ≥ 0.11 上,每個網絡接口的 mac 地址在os.networkInterfaces()
的輸出中,例如
require('os').networkInterfaces()
{ eth0:
[ { address: 'fe80::cae0:ebff:fe14:1dab',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: 'c8:e0:eb:14:1d:ab',
scopeid: 4,
internal: false },
{ address: '192.168.178.22',
netmask: '255.255.255.0',
family: 'IPv4',
mac: 'c8:e0:eb:14:1d:ab',
internal: false } ] }
在 NodeJS ≤ 0.10 中,您需要自己找出 mac 地址,但是有一些軟件包可以幫助您解決這個問題: node-macaddress (免責聲明:我是該軟件包的作者)。
該軟件包還為您的主機選擇了一個接口,以便您可以只做
require('node-macaddress').one(function (err, addr) { console.log(addr); }
在節點 ≥ 0.11 上,您不需要使用異步版本:
var addr = require('node-macaddress').one();
由於您通常只對“主機 macaddress”感興趣(盡管沒有主機可以有多個網絡接口,每個接口都有一個單獨的 mac 地址),因此此調用將為您提供准確的信息。
Node.JS 腳本可以通過檢查本地鏈路 IPv6 地址來發現當前機器的 MAC 地址。 (警告:這要求 IPv6 堆棧在 O/S 中處於活動狀態,這越來越普遍)
例如
LL: fe80::0211:22ff:fe33:4455
MAC: 0011:22 33:4455
基於http://en.wikipedia.org/wiki/IPv6_address#Modified_EUI-64
在 Windows 上,有必要通過運行提升的命令來停用 randomizeidentifiers:
netsh interface ipv6 set global randomizeidentifiers=disabled
以下代碼使用此技術生成 Variant 1 UUID(尾生成僅發生一次):
function generateUUID() {
generateUUID.tail = generateUUID.tail || (function(nics) {
var nic, index, addr, retn;
for (nic in nics) { // try to obtain the MAC address from the IPv6 scope-local address
for (index in nics[nic]) {
addr = nics[nic][index];
if (!addr.internal) {
if (addr.address.indexOf('fe80::') === 0) { // found scope-local
retn = retn || addr.address.slice(6).split(/:/).map(function(v, i, a) {
return parseInt(v, 16);
});
}
}
}
}
if (!retn) { // no IPv6 so generate random MAC with multicast bit set
index = Math.pow(2, 16);
retn = [];
retn.push(Math.floor(Math.random() * index) | 0x1000); // set multicast bit
retn.push(Math.floor(Math.random() * index));
retn.push(Math.floor(Math.random() * index));
retn.push(Math.floor(Math.random() * index));
}
retn[3] = 0x10000 | retn[3];
retn[2] = 0x10000 | retn[1] & 0xff00 | retn[2] & 0x00ff; // eliminate FFFE from xxxx:xxFF:FExx:xxxx
retn[1] = 0x10000 | retn[0] ^ 0x0200; // invert bit#41
retn[0] = 0x18000 | process.pid & 0x3fff;
retn = retn.map(function(v, i, a) {
return v.toString(16).slice(1)
});
return retn[0] + '-' + retn[1] + retn[2] + retn[3];
})(require('os').networkInterfaces());
var head = process.hrtime(), now = Math.floor(Date.now() / 1000);
head[1] = Math.floor(head[1] * 0.268435456); // 2^28 / 10^9
head[2] = (0x11000 | head[1] & 0x0fff).toString(16).slice(1);
head[1] = (0x10000 | head[1] >>> 12 & 0xffff).toString(16).slice(1);
head[0] = (4294967296 + now).toString(16).slice(1);
return head.concat(generateUUID.tail).join('-');
};
您需要在命令提示符/終端中使用npm install getmac安裝getmac node_module。 然后,它將起作用。
使用終端安裝包getmac 。
npm install --save getmac
在節點中使用
const getmac = require('getmac')
const callMac = () =>{
return getmac.default()
}
輸出>>“00:05:1b:61:d3:05”
您必須使用 root 用戶或命令運行它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.