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