I am working with a service in node.js that communicate with different machines. Each machine should have a unique identifier when the service emit an event to the main server, so we need to use the mac address of ethernet interface. I am kind of new to the "os module", but there is a build in method for that:
const os = require('os');
os.networkInterfaces();
I searched for it a lot but I am not quite sure about the names: when we log os.networkInterfaces() it gives an object with keys as interface name and values as an array of interfaces info- generally for ipv4 & ipv6. In linux the name of the ethernet interface should start with: "eth", in mac: "en", in windows it called "Ethernet" or sometimes: "vEthernet (WSL)", for example:
platform: win32
os.networkInterfaces(): {
'Ethernet 5': [
{
address: 'fe80::dd29:8ae9:2050:2de8',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: 'xx:xx:xx:xx:xx:xx',
internal: false,
cidr: 'fe80::dd29:8ae9:2050:2de8/64',
scopeid: 18
},
{
address: '10.212.134.202',
netmask: '255.255.255.255',
family: 'IPv4',
mac: 'xx:xx:xx:xx:xx:xx',
internal: false,
cidr: '10.212.134.202/32'
}
],
In general, I can do something like:
const interfaces = os.networkInterfaces();
let my_mac_address;
if(os.platform()==='win32') {
my_mac_address = interfaces['Ethernet 5'].filter(i => i.family === 'IPv4').mac;
}
but is there a clear rule about the names in each os? for example in win it will always include or start with: "Ethernet " etc - if so, I can write a function that search for a value with a given partial key (something like: how to get value from object with a partial index value javascript).
The reason for this is that those machines are in production and I do not have an access to check the ethernets connections names.. In addition, this method does not show any interfaces which do not have a connection since boot. Meaning if I have several interfaces, say eth0, eth1 where only eth0 has ever been connected. This method will only show eth0 and not eth1. There are also virtual interfaces which I dont understand the difference between them and the regular.
So how can I be sure that I am taking the proper ethernet interface mac address?
I can also use a npm package: node-macaddress. According their docs it: "Retrieves the MAC address of the given iface. If iface is omitted, this function automatically chooses an appropriate device (e.g. eth0 in Linux, en0 in OS X, etc.)."
"This library allows to discover the MAC address per network interface and chooses an appropriate interface if all you're interested in is one MAC address identifying the host system (see API + Examples below)"
But our preference is to work with the build in modules of node and do not install a package since every machine is running with different node version and things might break when we run build.
thanks for any help!