UNPKG

1.03 kBJavaScriptView Raw
1"use strict";
2
3const net = require("net");
4const execa = require("execa");
5const dests = ["default", "0.0.0.0", "0.0.0.0/0", "::", "::/0"];
6
7const args = {
8 v4: ["-rn", "-f", "inet"],
9 v6: ["-rn", "-f", "inet6"],
10};
11
12const parse = stdout => {
13 let result;
14
15 (stdout || "").trim().split("\n").some(line => {
16 const [target, gateway, _, iface] = line.split(/ +/) || [];
17 if (dests.includes(target) && gateway && net.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
30const promise = async family => {
31 const {stdout} = await execa("netstat", args[family]);
32 return parse(stdout);
33};
34
35const sync = family => {
36 const {stdout} = execa.sync("netstat", args[family]);
37 return parse(stdout);
38};
39
40module.exports.v4 = () => promise("v4");
41module.exports.v6 = () => promise("v6");
42
43module.exports.v4.sync = () => sync("v4");
44module.exports.v6.sync = () => sync("v6");