UNPKG

1.25 kBJavaScriptView Raw
1'use strict'
2Object.defineProperty(exports, '__esModule', { value: true })
3exports.isMAC = void 0
4// Prepare
5const os_1 = require('os')
6const macRegex = /(?:[a-z0-9]{1,2}[:-]){5}[a-z0-9]{1,2}/i
7const zeroRegex = /(?:[0]{1,2}[:-]){5}[0]{1,2}/
8/**
9 * Get the first proper MAC address
10 * @param iface If provided, restrict MAC address fetching to this interface
11 */
12function getMAC(iface) {
13 const list = os_1.networkInterfaces()
14 if (iface) {
15 const parts = list[iface]
16 if (!parts) {
17 throw new Error(`interface ${iface} was not found`)
18 }
19 for (const part of parts) {
20 if (zeroRegex.test(part.mac) === false) {
21 return part.mac
22 }
23 }
24 throw new Error(`interface ${iface} had no valid mac addresses`)
25 } else {
26 for (const [key, parts] of Object.entries(list)) {
27 // for some reason beyond me, this is needed to satisfy typescript
28 // fix https://github.com/bevry/getmac/issues/100
29 if (!parts) continue
30 for (const part of parts) {
31 if (zeroRegex.test(part.mac) === false) {
32 return part.mac
33 }
34 }
35 }
36 }
37 throw new Error('failed to get the MAC address')
38}
39exports.default = getMAC
40/** Check if the input is a valid MAC address */
41function isMAC(macAddress) {
42 return macRegex.test(macAddress)
43}
44exports.isMAC = isMAC