linux.js 1.5 KB

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