I would like to know if there is a way of having NODE retrieve the MAC address(es) of the server on which it is running.
Node has no built-in was to access this kind of low-level data.
However, you could execute ifconfig
and parse its output or write a C++ extension for node that provides a function to retrieve the mac address. An even easier way is reading /sys/class/net/eth?/address
:
var fs = require('fs'),
path = require('path');
function getMACAddresses() {
var macs = {}
var devs = fs.readdirSync('/sys/class/net/');
devs.forEach(function(dev) {
var fn = path.join('/sys/class/net', dev, 'address');
if(dev.substr(0, 3) == 'eth' && fs.existsSync(fn)) {
macs[dev] = fs.readFileSync(fn).toString().trim();
}
});
return macs;
}
console.log(getMACAddresses());
The function returns an object containing the mac addresses of all eth*
devices. If you want all devices that have one, even if they are e.g. called wlan*
, simply remove the dev.substr(0, 3) == 'eth'
check.
If you're just looking for a unique server id, you could take the mongodb/bson approach and use the first n bytes of the md5 hash of the server's host name:
var machineHash = crypto.createHash('md5').update(os.hostname()).digest('binary');
This code is from node-buffalo. Not perfect, but may be good enough depending on what you're trying to do.
I found the solution using balupton's getmac: https://npmjs.org/package/getmac
I tried the getmac package but it would not work for me (node v0.10, Mac OS X) - so I set out and built my own: https://github.com/scravy/node-macaddress . It works in Windows, OS X, Linux, and probably every unix with ifconfig
:-)