如何使用Node.js获取Linux和Unix系统的Mac地址

时间:2019-04-22 14:19:12

标签: node.js

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地址。

2 个答案:

答案 0 :(得分:1)

  

如果您不想使用第三方服务,则可以使用try (DirectoryStream<Path> pictures = Files.newDirectoryStream(Paths.get(dirPath), "*.png")) { for (Path picture : pictures) { if (Files.isRegularFile(picture)) { cardList.add( new Card(picture.getFileName().toString(), cardPath)); } } } catch (IOException e) { e.printStackTrace(); } 模块

os

答案 1 :(得分:0)

您可以使用此库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

希望这会有所帮助!