Projekt

Obecné

Profil

Stáhnout (1.52 KB) Statistiky
| Větev: | Revize:
1
"use strict";
2

    
3
const net = require("net");
4
const os = require("os");
5
const execa = require("execa");
6

    
7
const args = {
8
  v4: ["-4", "r"],
9
  v6: ["-6", "r"],
10
};
11

    
12
const parse = (stdout, family) => {
13
  let result;
14

    
15
  (stdout || "").trim().split("\n").some(line => {
16
    const results = /default( via .+?)?( dev .+?)( |$)/.exec(line) || [];
17
    const gateway = (results[1] || "").substring(5);
18
    const iface = (results[2] || "").substring(5);
19
    if (gateway && net.isIP(gateway)) { // default via 1.2.3.4 dev en0
20
      result = {gateway, interface: (iface ? iface : null)};
21
      return true;
22
    } else if (iface && !gateway) { // default via dev en0
23
      const interfaces = os.networkInterfaces();
24
      const addresses = interfaces[iface];
25
      if (!addresses || !addresses.length) return;
26

    
27
      addresses.some(addr => {
28
        if (addr.family.substring(2) === family && net.isIP(addr.address)) {
29
          result = {gateway: addr.address, interface: (iface ? iface : null)};
30
          return true;
31
        }
32
      });
33
    }
34
  });
35

    
36
  if (!result) {
37
    throw new Error("Unable to determine default gateway");
38
  }
39

    
40
  return result;
41
};
42

    
43
const promise = family => {
44
  return execa.stdout("ip", args[family]).then(stdout => {
45
    return parse(stdout, family);
46
  });
47
};
48

    
49
const sync = family => {
50
  const result = execa.sync("ip", args[family]);
51
  return parse(result.stdout, family);
52
};
53

    
54
module.exports.v4 = () => promise("v4");
55
module.exports.v6 = () => promise("v6");
56

    
57
module.exports.v4.sync = () => sync("v4");
58
module.exports.v6.sync = () => sync("v6");
(8-8/12)