pooliot-client
Version:
61 lines (50 loc) • 1.68 kB
JavaScript
import { networkInterfaces } from 'os';
import { execSync } from 'child_process';
const MAC_REGEXP = /(?:ether|HWaddr)\s+((?:[a-z0-9]{2}:){5}[a-z0-9]{2})/i;
export default () => {
const interfaces = networkInterfaces();
const macAddresses = []
.concat(
...Object.keys(interfaces)
.filter(key => key !== 'lo')
.map(key => interfaces[key].map(item => ({ interface: key, ...item }))),
)
.map(i => i.mac)
.filter(mac => mac && mac !== '00:00:00:00:00:00' && !mac.startsWith('00:00:00:00:'))
.filter((value, index, array) => array.indexOf(value) === index);
if (!macAddresses.length) {
console.warn('no mac addresses, falling back to ifconfig');
const ifConfig = execSync('ifconfig').toString();
macAddresses.push(
...ifConfig
.split('\n')
.map(line => line.match(MAC_REGEXP))
.filter(Boolean)
.map(match => match[1])
.filter(mac => mac && mac !== '00:00:00:00:00:00')
.filter((value, index, array) => array.indexOf(value) === index),
);
}
for (let key of Object.keys(interfaces)) {
if (key === 'lo') continue;
let netInterface = interfaces[key];
let filtered = netInterface.filter(item => item.family === 'IPv4');
if (filtered.length !== 0) {
netInterface = filtered;
}
for (let item of netInterface) {
if (!item.mac || !item.address) {
continue;
}
if (item.address === '127.0.0.1' || item.address === '::1') {
continue;
}
return {
macAddresses,
mac: item.mac,
ip: item.address,
};
}
}
throw new Error('Could not find valid ip address');
};