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.
相关问题
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- google-drive can't get push notifications
- How to reimport module with ES6 import
- Why is `node.js` dying when called from inside pyt
- How to verify laravel passport api token in node /
相关文章
- node连接远程oracle报错
- How can make folder with Firebase Cloud Functions
- @angular-cli install fails with deprecated request
- node.js modify file data stream?
- How to resolve hostname to an ip address in node j
- Transactionally writing files in Node.js
- Log to node console or debug during webpack build
- Get file created date in node
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
:-)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
: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. calledwlan*
, simply remove thedev.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:
This code is from node-buffalo. Not perfect, but may be good enough depending on what you're trying to do.
Here is node.js code using command line tools to get MAC address:
for wlan0
In node.js, use this - save the code to getMAC.js - "$ node getMAC.js" to run
The complete answer is further down, but basically you can get that info in vanilla node.js via:
This gives you all the info about networking devices on the system, including MAC addresses for each interface.
You can further narrow this down to just the MACS:
And further, to the pure MAC addresses:
This last one will give you an array-like match object of the form:
['00:00:00:00:00:00', 'A8:AE:B6:58:C5:09', 'FC:E3:5A:42:80:18' ]
The first element is your lo or local interface.
I randomly generated the others for public example using https://www.miniwebtool.com/mac-address-generator/
If you want to be more 'proper' (or break it down into easier to digest steps):
Basically, you're taking the interface data object and converting it into a JSON text string. The. you get a match object for the mac addresses and convert that into a text string. Then you extract only the MAC addresses into an iteratable match object that contains only each MAC in each element.
There are surly more succinct ways of doing this, but this one is reliable and easy to read.