freebsd.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. const net = require("net");
  3. const execa = require("execa");
  4. const dests = ["default", "0.0.0.0", "0.0.0.0/0", "::", "::/0"];
  5. const args = {
  6. v4: ["-rn", "-f", "inet"],
  7. v6: ["-rn", "-f", "inet6"],
  8. };
  9. const parse = stdout => {
  10. let result;
  11. (stdout || "").trim().split("\n").some(line => {
  12. const results = line.split(/ +/) || [];
  13. const target = results[0];
  14. const gateway = results[1];
  15. const iface = results[3];
  16. if (dests.indexOf(target) !== -1 && gateway && net.isIP(gateway)) {
  17. result = {gateway, interface: (iface ? iface : null)};
  18. return true;
  19. }
  20. });
  21. if (!result) {
  22. throw new Error("Unable to determine default gateway");
  23. }
  24. return result;
  25. };
  26. const promise = family => {
  27. return execa.stdout("netstat", args[family]).then(stdout => {
  28. return parse(stdout);
  29. });
  30. };
  31. const sync = family => {
  32. const result = execa.sync("netstat", args[family]);
  33. return parse(result.stdout);
  34. };
  35. module.exports.v4 = () => promise("v4");
  36. module.exports.v6 = () => promise("v6");
  37. module.exports.v4.sync = () => sync("v4");
  38. module.exports.v6.sync = () => sync("v6");