1 | "use strict";
|
---|
2 |
|
---|
3 | const net = require("net");
|
---|
4 | const execa = require("execa");
|
---|
5 | const dests = ["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[3];
|
---|
20 | if (dests.indexOf(target) !== -1 && gateway && net.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 = family => {
|
---|
34 | return execa.stdout("netstat", args[family]).then(stdout => {
|
---|
35 | return parse(stdout);
|
---|
36 | });
|
---|
37 | };
|
---|
38 |
|
---|
39 | const sync = family => {
|
---|
40 | const result = execa.sync("netstat", args[family]);
|
---|
41 | return parse(result.stdout);
|
---|
42 | };
|
---|
43 |
|
---|
44 | module.exports.v4 = () => promise("v4");
|
---|
45 | module.exports.v6 = () => promise("v6");
|
---|
46 |
|
---|
47 | module.exports.v4.sync = () => sync("v4");
|
---|
48 | module.exports.v6.sync = () => sync("v6");
|
---|