Can I fetch a unique server machine identifier with node.js?

clayperez picture clayperez · Jun 23, 2012 · Viewed 8k times · Source

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.

Answer

ThiefMaster picture ThiefMaster · Jun 23, 2012

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.