|
| 1 | +const fs = require('fs'); |
| 2 | +const arpping = require('arpping')({}); |
| 3 | + |
| 4 | +class Zeroconf { |
| 5 | + /** |
| 6 | + * Build the ARP table |
| 7 | + * @param ip |
| 8 | + * @returns {Promise<unknown>} |
| 9 | + */ |
| 10 | + static getArpTable(ip = null) { |
| 11 | + return new Promise((resolve, reject) => { |
| 12 | + arpping.discover(ip, (err, hosts) => { |
| 13 | + if (err) { |
| 14 | + return reject(err); |
| 15 | + } |
| 16 | + const arpTable = Zeroconf.fixMacAddresses(hosts); |
| 17 | + return resolve(arpTable); |
| 18 | + }); |
| 19 | + }); |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * Sometime arp command returns mac addresses without leading zeroes. |
| 24 | + * @param hosts |
| 25 | + */ |
| 26 | + static fixMacAddresses(hosts) { |
| 27 | + return hosts.map(host => { |
| 28 | + const octets = host.mac.split(':'); |
| 29 | + |
| 30 | + const fixedMac = octets.map(octet => { |
| 31 | + if (octet.length === 1) { |
| 32 | + return `0${octet}`; |
| 33 | + } |
| 34 | + return octet; |
| 35 | + }); |
| 36 | + |
| 37 | + return { |
| 38 | + ip: host.ip, |
| 39 | + mac: fixedMac.join(':'), |
| 40 | + }; |
| 41 | + }); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Save ARP table to local file |
| 46 | + * @param config |
| 47 | + * @returns {Promise<{error: string}|{file: {request: string; resolved: string} | any | string | string, status: string}>} |
| 48 | + */ |
| 49 | + static async saveArpTable(config = {}) { |
| 50 | + const ip = config.ip || null; |
| 51 | + const fileName = config.file || './arp-table.json'; |
| 52 | + try { |
| 53 | + const arpTable = await Zeroconf.getArpTable(ip); |
| 54 | + const jsonContent = JSON.stringify(arpTable, null, 2); |
| 55 | + fs.writeFileSync(fileName, jsonContent, 'utf8'); |
| 56 | + return { status: 'ok', file: fileName }; |
| 57 | + } catch (e) { |
| 58 | + return { error: e.toString() }; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Read ARP table file |
| 64 | + * @param fileName |
| 65 | + * @returns {Promise<{error: string}|any>} |
| 66 | + */ |
| 67 | + static async loadArpTable(fileName = './arp-table.json') { |
| 68 | + try { |
| 69 | + const jsonContent = await fs.readFileSync(fileName); |
| 70 | + return JSON.parse(jsonContent); |
| 71 | + } catch (e) { |
| 72 | + return { error: e.toString() }; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * Read devices cache file |
| 78 | + * @param fileName |
| 79 | + * @returns {Promise<{error: string}>} |
| 80 | + */ |
| 81 | + static async loadCachedDevices(fileName = './devices-cache.json') { |
| 82 | + try { |
| 83 | + const jsonContent = await fs.readFileSync(fileName); |
| 84 | + return JSON.parse(jsonContent); |
| 85 | + } catch (e) { |
| 86 | + return { error: e.toString() }; |
| 87 | + } |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +module.exports = Zeroconf; |
0 commit comments