| [9af201e] | 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 [target, gateway, _, iface] = line.split(/ +/) || [];
|
|---|
| 17 | if (dests.has(target) && gateway && isIP(gateway)) {
|
|---|
| 18 | result = {gateway, interface: (iface ? iface : null)};
|
|---|
| 19 | return true;
|
|---|
| 20 | }
|
|---|
| 21 | });
|
|---|
| 22 |
|
|---|
| 23 | if (!result) {
|
|---|
| 24 | throw new Error("Unable to determine default gateway");
|
|---|
| 25 | }
|
|---|
| 26 |
|
|---|
| 27 | return result;
|
|---|
| 28 | };
|
|---|
| 29 |
|
|---|
| 30 | const promise = async family => {
|
|---|
| 31 | const {stdout} = await execa("netstat", args[family]);
|
|---|
| 32 | return parse(stdout);
|
|---|
| 33 | };
|
|---|
| 34 |
|
|---|
| 35 | const sync = family => {
|
|---|
| 36 | const {stdout} = execa.sync("netstat", args[family]);
|
|---|
| 37 | return parse(stdout);
|
|---|
| 38 | };
|
|---|
| 39 |
|
|---|
| 40 | module.exports.v4 = () => promise("v4");
|
|---|
| 41 | module.exports.v6 = () => promise("v6");
|
|---|
| 42 |
|
|---|
| 43 | module.exports.v4.sync = () => sync("v4");
|
|---|
| 44 | module.exports.v6.sync = () => sync("v6");
|
|---|