openbsd.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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[7];
  16. if (dests.includes(target) && 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 = async family => {
  27. const {stdout} = await execa("netstat", args[family]);
  28. return parse(stdout);
  29. };
  30. const sync = family => {
  31. const {stdout} = execa.sync("netstat", args[family]);
  32. return parse(stdout);
  33. };
  34. module.exports.v4 = () => promise("v4");
  35. module.exports.v6 = () => promise("v6");
  36. module.exports.v4.sync = () => sync("v4");
  37. module.exports.v6.sync = () => sync("v6");