[英]How to get mac address of a Linux and Unix system using Nodejs
lib.mac = function () {
var macAddress = undefined;
Object.keys(ifaces).forEach(function (ifname) {
var alias = 0;
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal != false) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return;
}
if (alias >= 1) {
// this single interface has multiple ipv4 addresses
macAddress = iface.mac;
} else {
// this interface has only one ipv4 adress
macAddress = iface.mac;
}
++alias;
});
});
return macAddress;
}
上面是我的Windows系統代碼,我不知道如何獲取Linux和Unix系統的mac地址。
如果您不想使用第三方服務,則可以使用
os
模塊
require("os").networkInterfaces()
{ lo:
[ { address: '127.0.0.1',
netmask: '255.0.0.0',
family: 'IPv4',
mac: '00:00:00:00:00:00',
internal: true,
cidr: '127.0.0.1/8' },
{ address: '::1',
netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
family: 'IPv6',
mac: '00:00:00:00:00:00',
scopeid: 0,
internal: true,
cidr: '::1/128' } ],
enp0s31f6:
[ { address: '172.22.100.113',
netmask: '255.255.255.0',
family: 'IPv4',
mac: '8c:16:45:f0:8f:51',
internal: false,
cidr: '172.22.100.113/24' },
{ address: 'fe80:fe23:adaa:583d:123c',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: '8c:16:45:f0:8f:51',
scopeid: 2,
internal: false,
cidr: 'fe80::4dd7:aeee:583d:7c7c/64' } ],
...
您可以使用此lib getmac 。
例如。:
// Fetch the computer's mac address
require('getmac').getMac(function(err, macAddress){
if (err) throw err
console.log(macAddress)
});
或僅使用os
模塊:
require("os").networkInterfaces();
{ lo:
[ { address: '127.0.0.1',
netmask: '255.0.0.0',
family: 'IPv4',
mac: '00:00:00:00:00:00',
internal: true,
cidr: '127.0.0.1/8' },
{ address: '::1',
netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
family: 'IPv6',
mac: '00:00:00:00:00:00',
scopeid: 0,
internal: true,
cidr: '::1/128' } ],
enp2s0:
[ { address: '192.168.1.10',
netmask: '255.255.254.0',
family: 'IPv4',
mac: '94:de:80:f0:ef:ef',
internal: false,
cidr: '192.168.4.144/23' },
{ address: 'fe80::ca45:44ac:89f4:85',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: '94:de:80:f0:ef:ef',
scopeid: 2,
internal: false,
cidr: 'fe80::ca45:44ac:89f4:85/64' }
],
}
https://nodejs.org/api/os.html#os_os_networkinterfaces
https://www.npmjs.com/package/getmac
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.