简体   繁体   中英

NodeJS - How to get remote IP Address

For my project, I need to fetch the remote IP address of another NodeJS Server. In fact, in many countries such as Belgium, the IP address of a computer provided by the telecom is not a fixed IP and can change every xx hours.

I need to know how I can get the Internet IP address of a remote NodeJs computer in real-time.

Example: an internet provider change the IP of a nodeJS computer: I want to know in "relative" real-time the new IP.

Thanks to much, visualight

If the remote server you want to communicate with switches its ip address and doesn't tell you (as in, contacts your server in some way), you are basically out of luck.

If there is a domain pointing to the other machine, you could use this snippet (which I shamelessly copied from the official docs ) to force a DNS resolve:

var dns = require('dns');

dns.resolve4('www.google.com', function (err, addresses) {
  if (err) throw err;

  console.log('addresses: ' + JSON.stringify(addresses));

  addresses.forEach(function (a) {
    dns.reverse(a, function (err, domains) {
      if (err) {
        throw err;
      }

      console.log('reverse for ' + a + ': ' + JSON.stringify(domains));
    });
  });
});

UPDATE: There is module on npm that allows you to get the public ip address of a machine. Its very simple, as it just does a request against curlmyip.com and returns the result. You could set up some polling interval using setInterval and send it to the other nodes whenever you detect a change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM