source: trip-planner-front/node_modules/default-gateway/linux.js@ e29cc2e

Last change on this file since e29cc2e was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.5 KB
Line 
1"use strict";
2
3const net = require("net");
4const os = require("os");
5const execa = require("execa");
6
7const args = {
8 v4: ["-4", "r"],
9 v6: ["-6", "r"],
10};
11
12const 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 && net.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 = os.networkInterfaces();
24 const addresses = interfaces[iface];
25 if (!addresses || !addresses.length) return;
26
27 addresses.some(addr => {
28 if (addr.family.substring(2) === family && net.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
43const promise = family => {
44 return execa.stdout("ip", args[family]).then(stdout => {
45 return parse(stdout, family);
46 });
47};
48
49const sync = family => {
50 const result = execa.sync("ip", args[family]);
51 return parse(result.stdout, family);
52};
53
54module.exports.v4 = () => promise("v4");
55module.exports.v6 = () => promise("v6");
56
57module.exports.v4.sync = () => sync("v4");
58module.exports.v6.sync = () => sync("v6");
Note: See TracBrowser for help on using the repository browser.