freebsd.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 [target, gateway, _, iface] = line.split(/ +/) || [];
  13. if (dests.includes(target) && gateway && net.isIP(gateway)) {
  14. result = {gateway, interface: (iface ? iface : null)};
  15. return true;
  16. }
  17. });
  18. if (!result) {
  19. throw new Error("Unable to determine default gateway");
  20. }
  21. return result;
  22. };
  23. const promise = async family => {
  24. const {stdout} = await execa("netstat", args[family]);
  25. return parse(stdout);
  26. };
  27. const sync = family => {
  28. const {stdout} = execa.sync("netstat", args[family]);
  29. return parse(stdout);
  30. };
  31. module.exports.v4 = () => promise("v4");
  32. module.exports.v6 = () => promise("v6");
  33. module.exports.v4.sync = () => sync("v4");
  34. module.exports.v6.sync = () => sync("v6");