1 | "use strict";
|
2 |
|
3 | const {isIP} = require("net");
|
4 | const execa = require("execa");
|
5 | const dests = new Set(["default", "0.0.0.0", "0.0.0.0/0", "::", "::/0"]);
|
6 |
|
7 | const args = {
|
8 | v4: ["-rn", "-f", "inet"],
|
9 | v6: ["-rn", "-f", "inet6"],
|
10 | };
|
11 |
|
12 | const parse = stdout => {
|
13 | let result;
|
14 |
|
15 | (stdout || "").trim().split("\n").some(line => {
|
16 | const results = line.split(/ +/) || [];
|
17 | const target = results[0];
|
18 | const gateway = results[1];
|
19 | const iface = results[7];
|
20 | if (dests.has(target) && gateway && isIP(gateway)) {
|
21 | result = {gateway, interface: (iface ? iface : null)};
|
22 | return true;
|
23 | }
|
24 | });
|
25 |
|
26 | if (!result) {
|
27 | throw new Error("Unable to determine default gateway");
|
28 | }
|
29 |
|
30 | return result;
|
31 | };
|
32 |
|
33 | const promise = async family => {
|
34 | const {stdout} = await execa("netstat", args[family]);
|
35 | return parse(stdout);
|
36 | };
|
37 |
|
38 | const sync = family => {
|
39 | const {stdout} = execa.sync("netstat", args[family]);
|
40 | return parse(stdout);
|
41 | };
|
42 |
|
43 | module.exports.v4 = () => promise("v4");
|
44 | module.exports.v6 = () => promise("v6");
|
45 |
|
46 | module.exports.v4.sync = () => sync("v4");
|
47 | module.exports.v6.sync = () => sync("v6");
|