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