myIpAddress.js 2.5 KB

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