All files / src getMAC.ts

100% Statements 21/21
100% Branches 15/15
100% Functions 3/3
100% Lines 21/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 414x     4x       4x 5x 5x   5x 4x 4x   4x 7x   7x 5x 5x   5x 3x   18x 3x 18x   2x             3x     4x  
import {
  networkInterfaces,
} from 'os';
import {
  strings,
} from './strings';
 
export function getMAC(): Uint8Array {
  const interfaces = networkInterfaces();
  const interfaceNames = Object.keys(interfaces);
 
  for (let ii = 0; ii < interfaceNames.length; ii += 1) {
    const interfaceName = interfaceNames[ii];
    const _interface = interfaces[interfaceName];
 
    for (let jj = 0; jj < _interface.length; jj += 1) {
      const val = _interface[jj];
 
      if (val && typeof val === 'object') {
        const mac = val.mac;
        const empty = '00:00:00:00:00:00';
 
        if (typeof mac === 'string' && mac && mac !== empty) {
          const bytes = mac
            .split(':')
            .map((byteStr) => parseInt(byteStr, 16));
          if (bytes.length === 6 &&
              bytes.filter((num) => num >= 0 && num <= 255).length === 6)
          {
            return new Uint8Array(bytes);
          }
        }
      }
    }
  }
 
  throw new Error(strings.MAC_ADDRESS_UNAVAILABLE);
}
 
export default getMAC;