You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

myIpAddress.js 1.0KB

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