Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

get the mac address of the current machine with node.js using getmac

I am working on this question.

Now I am trying to use getmac

to get the mac address of the current machine with node.js.

I followed the installation instructions. But when I run this code:

require('getmac').getMac(function(err,macAddress){
    if (err)  throw err;
    console.log(macAddress);    
});

I get this error:

Error: Command failed: the command "getmac" could not be found

Do you know how to get this to work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On NodeJS ≥ 0.11 the mac address for each network interface is in the output of os.networkInterfaces(), e.g.

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 } ] }

In NodeJS ≤ 0.10 you need to find out the mac addresses on your own, but there are packages to help you with that: node-macaddress (disclaimer: I am the author of said package).

This package also selects one interface for your host so that you can do just

require('node-macaddress').one(function (err, addr) { console.log(addr); }

On node ≥ 0.11 you are not required to use the asynchronous version:

var addr = require('node-macaddress').one();

Since you are typically only interested in "the hosts macaddress" (although there is no such thing as a host can have multiple network interfaces each having an individual mac address), this call will give you exactly that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...