UNPKG

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