linux.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 = family => {
  36. return execa.stdout("ip", args[family]).then(stdout => {
  37. return parse(stdout, family);
  38. });
  39. };
  40. const sync = family => {
  41. const result = execa.sync("ip", args[family]);
  42. return parse(result.stdout, family);
  43. };
  44. module.exports.v4 = () => promise("v4");
  45. module.exports.v6 = () => promise("v6");
  46. module.exports.v4.sync = () => sync("v4");
  47. module.exports.v6.sync = () => sync("v6");