myIpAddress.js 853 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /**
  2. * Module dependencies.
  3. */
  4. var net = require('net');
  5. /**
  6. * Module exports.
  7. */
  8. module.exports = myIpAddress;
  9. myIpAddress.async = true;
  10. /**
  11. * Returns the IP address of the host that the Navigator is running on, as
  12. * a string in the dot-separated integer format.
  13. *
  14. * Example:
  15. *
  16. * ``` js
  17. * myIpAddress()
  18. * // would return the string "198.95.249.79" if you were running the
  19. * // Navigator on that host.
  20. * ```
  21. *
  22. * @return {String} external IP address
  23. */
  24. function myIpAddress (fn) {
  25. // 8.8.8.8:53 is "Google Public DNS":
  26. // https://developers.google.com/speed/public-dns/
  27. var socket = net.connect({ host: '8.8.8.8', port: 53 });
  28. socket.once('error', fn);
  29. socket.once('connect', function () {
  30. socket.removeListener('error', fn);
  31. var ip = socket.address().address;
  32. socket.destroy();
  33. fn(null, ip);
  34. });
  35. }