android.js 997 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 results = /default via (.+?) dev (.+?)( |$)/.exec(line) || [];
  12. const gateway = results[1];
  13. const iface = results[2];
  14. if (gateway && net.isIP(gateway)) {
  15. result = {gateway, interface: (iface ? iface : null)};
  16. return true;
  17. }
  18. });
  19. if (!result) {
  20. throw new Error("Unable to determine default gateway");
  21. }
  22. return result;
  23. };
  24. const promise = family => {
  25. return execa.stdout("ip", args[family]).then(stdout => {
  26. return parse(stdout);
  27. });
  28. };
  29. const sync = family => {
  30. const result = execa.sync("ip", args[family]);
  31. return parse(result.stdout);
  32. };
  33. module.exports.v4 = () => promise("v4");
  34. module.exports.v6 = () => promise("v6");
  35. module.exports.v4.sync = () => sync("v4");
  36. module.exports.v6.sync = () => sync("v6");