-
-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathindex.ts
More file actions
41 lines (39 loc) · 1.15 KB
/
index.ts
File metadata and controls
41 lines (39 loc) · 1.15 KB
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
41
// Prepare
import { networkInterfaces } from 'os'
const macRegex = /(?:[a-z0-9]{1,2}[:-]){5}[a-z0-9]{1,2}/i
const zeroRegex = /(?:[0]{1,2}[:-]){5}[0]{1,2}/
/**
* Get the first proper MAC address
* @param iface If provided, restrict MAC address fetching to this interface
*/
export default function getMAC(iface?: string): string| Error {
const list = networkInterfaces()
if (iface) {
const parts = list[iface]
if (!parts) {
throw new Error(`interface ${iface} was not found`)
}
for (const part of parts) {
if (zeroRegex.test(part.mac) === false) {
return part.mac
}
}
throw new Error(`interface ${iface} had no valid mac addresses`)
} else {
for (const [_, parts] of Object.entries(list)) {
// for some reason beyond me, this is needed to satisfy typescript
// fix https://github.com/bevry/getmac/issues/100
if (!parts) continue
for (const part of parts) {
if (zeroRegex.test(part.mac) === false) {
return part.mac
}
}
}
}
throw new Error('failed to get the MAC address')
}
/** Check if the input is a valid MAC address */
export function isMAC(macAddress: string):boolean {
return macRegex.test(macAddress)
}