| [9af201e] | 1 | "use strict";
|
|---|
| 2 |
|
|---|
| 3 | const {isIP} = require("net");
|
|---|
| 4 | const {networkInterfaces} = require("os");
|
|---|
| 5 | const execa = require("execa");
|
|---|
| 6 |
|
|---|
| 7 | const args = {
|
|---|
| 8 | v4: ["-4", "r"],
|
|---|
| 9 | v6: ["-6", "r"],
|
|---|
| 10 | };
|
|---|
| 11 |
|
|---|
| 12 | const parse = (stdout, family) => {
|
|---|
| 13 | let result;
|
|---|
| 14 |
|
|---|
| 15 | (stdout || "").trim().split("\n").some(line => {
|
|---|
| 16 | const results = /default( via .+?)?( dev .+?)( |$)/.exec(line) || [];
|
|---|
| 17 | const gateway = (results[1] || "").substring(5);
|
|---|
| 18 | const iface = (results[2] || "").substring(5);
|
|---|
| 19 | if (gateway && isIP(gateway)) { // default via 1.2.3.4 dev en0
|
|---|
| 20 | result = {gateway, interface: (iface ? iface : null)};
|
|---|
| 21 | return true;
|
|---|
| 22 | } else if (iface && !gateway) { // default via dev en0
|
|---|
| 23 | const interfaces = networkInterfaces();
|
|---|
| 24 | const addresses = interfaces[iface];
|
|---|
| 25 | if (!addresses || !addresses.length) return;
|
|---|
| 26 |
|
|---|
| 27 | addresses.some(addr => {
|
|---|
| 28 | if (addr.family.substring(2) === family && isIP(addr.address)) {
|
|---|
| 29 | result = {gateway: addr.address, interface: (iface ? iface : null)};
|
|---|
| 30 | return true;
|
|---|
| 31 | }
|
|---|
| 32 | });
|
|---|
| 33 | }
|
|---|
| 34 | });
|
|---|
| 35 |
|
|---|
| 36 | if (!result) {
|
|---|
| 37 | throw new Error("Unable to determine default gateway");
|
|---|
| 38 | }
|
|---|
| 39 |
|
|---|
| 40 | return result;
|
|---|
| 41 | };
|
|---|
| 42 |
|
|---|
| 43 | const promise = async family => {
|
|---|
| 44 | const {stdout} = await execa("ip", args[family]);
|
|---|
| 45 | return parse(stdout, family);
|
|---|
| 46 | };
|
|---|
| 47 |
|
|---|
| 48 | const sync = family => {
|
|---|
| 49 | const {stdout} = execa.sync("ip", args[family]);
|
|---|
| 50 | return parse(stdout, family);
|
|---|
| 51 | };
|
|---|
| 52 |
|
|---|
| 53 | module.exports.v4 = () => promise("v4");
|
|---|
| 54 | module.exports.v6 = () => promise("v6");
|
|---|
| 55 |
|
|---|
| 56 | module.exports.v4.sync = () => sync("v4");
|
|---|
| 57 | module.exports.v6.sync = () => sync("v6");
|
|---|