win32.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. const execa = require("execa");
  3. const ipRegex = require("ip-regex");
  4. const gwArgs = "path Win32_NetworkAdapterConfiguration where IPEnabled=true get DefaultIPGateway,Index /format:table".split(" ");
  5. const ifArgs = "path Win32_NetworkAdapter get Index,NetConnectionID /format:table".split(" ");
  6. const parse = (gwTable, ifTable, family) => {
  7. let gateway, gwid, result;
  8. (gwTable || "").trim().split("\n").splice(1).some(line => {
  9. const results = line.trim().split(/} +/) || [];
  10. const gw = results[0];
  11. const id = results[1];
  12. gateway = (ipRegex[family]().exec((gw || "").trim()) || [])[0];
  13. if (gateway) {
  14. gwid = id;
  15. return true;
  16. }
  17. });
  18. (ifTable || "").trim().split("\n").splice(1).some(line => {
  19. const i = line.indexOf(" ");
  20. const id = line.substr(0, i).trim();
  21. const name = line.substr(i + 1).trim();
  22. if (id === gwid) {
  23. result = {gateway, interface: name ? name : null};
  24. return true;
  25. }
  26. });
  27. if (!result) {
  28. throw new Error("Unable to determine default gateway");
  29. }
  30. return result;
  31. };
  32. const spawnOpts = {
  33. windowsHide: true,
  34. };
  35. const promise = family => {
  36. return Promise.all([
  37. execa.stdout("wmic", gwArgs, spawnOpts),
  38. execa.stdout("wmic", ifArgs, spawnOpts),
  39. ]).then(results => {
  40. const gwTable = results[0];
  41. const ifTable = results[1];
  42. return parse(gwTable, ifTable, family);
  43. });
  44. };
  45. const sync = family => {
  46. const gwTable = execa.sync("wmic", gwArgs, spawnOpts).stdout;
  47. const ifTable = execa.sync("wmic", ifArgs, spawnOpts).stdout;
  48. return parse(gwTable, ifTable, family);
  49. };
  50. module.exports.v4 = () => promise("v4");
  51. module.exports.v6 = () => promise("v6");
  52. module.exports.v4.sync = () => sync("v4");
  53. module.exports.v6.sync = () => sync("v6");