myIpAddress.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. const ip_1 = require("./ip");
  7. const net_1 = __importDefault(require("net"));
  8. /**
  9. * Returns the IP address of the host that the Navigator is running on, as
  10. * a string in the dot-separated integer format.
  11. *
  12. * Example:
  13. *
  14. * ``` js
  15. * myIpAddress()
  16. * // would return the string "198.95.249.79" if you were running the
  17. * // Navigator on that host.
  18. * ```
  19. *
  20. * @return {String} external IP address
  21. */
  22. async function myIpAddress() {
  23. return new Promise((resolve, reject) => {
  24. // 8.8.8.8:53 is "Google Public DNS":
  25. // https://developers.google.com/speed/public-dns/
  26. const socket = net_1.default.connect({ host: '8.8.8.8', port: 53 });
  27. const onError = () => {
  28. // if we fail to access Google DNS (as in firewall blocks access),
  29. // fallback to querying IP locally
  30. resolve(ip_1.ip.address());
  31. };
  32. socket.once('error', onError);
  33. socket.once('connect', () => {
  34. socket.removeListener('error', onError);
  35. const addr = socket.address();
  36. socket.destroy();
  37. if (typeof addr === 'string') {
  38. resolve(addr);
  39. }
  40. else if (addr.address) {
  41. resolve(addr.address);
  42. }
  43. else {
  44. reject(new Error('Expected a `string`'));
  45. }
  46. });
  47. });
  48. }
  49. exports.default = myIpAddress;
  50. //# sourceMappingURL=myIpAddress.js.map