android.js 941 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. "use strict";
  2. const net = require("net");
  3. const execa = require("execa");
  4. const args = {
  5. v4: ["-4", "r"],
  6. v6: ["-6", "r"],
  7. };
  8. const parse = stdout => {
  9. let result;
  10. (stdout || "").trim().split("\n").some(line => {
  11. const [_, gateway, iface] = /default via (.+?) dev (.+?)( |$)/.exec(line) || [];
  12. if (gateway && net.isIP(gateway)) {
  13. result = {gateway, interface: (iface ? iface : null)};
  14. return true;
  15. }
  16. });
  17. if (!result) {
  18. throw new Error("Unable to determine default gateway");
  19. }
  20. return result;
  21. };
  22. const promise = async family => {
  23. const {stdout} = await execa("ip", args[family]);
  24. return parse(stdout, family);
  25. };
  26. const sync = family => {
  27. const {stdout} = execa.sync("ip", args[family]);
  28. return parse(stdout);
  29. };
  30. module.exports.v4 = () => promise("v4");
  31. module.exports.v6 = () => promise("v6");
  32. module.exports.v4.sync = () => sync("v4");
  33. module.exports.v6.sync = () => sync("v6");