我可以使用node.js获取唯一的服务器机器标识符吗? [英] Can I fetch a unique server machine identifier with node.js?
问题描述
我想知道是否有让NODE检索运行它的服务器的MAC地址的方法.
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.
但是,您可以执行ifconfig
并解析其输出,或者为节点编写C ++扩展,该扩展提供了检索mac地址的功能.甚至更简单的方法是阅读/sys/class/net/eth?/address
:
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());
该函数返回一个对象,其中包含所有eth*
设备的mac地址.如果您想让所有设备都拥有一个,即使它们是称为wlan*
,只需删除dev.substr(0, 3) == 'eth'
检查.
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.
这篇关于我可以使用node.js获取唯一的服务器机器标识符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!