How to get my external IP address with node.js?

后端 未结 14 1506
情深已故
情深已故 2020-12-06 05:00

I\'m using node.js and I need to get my external IP address, provided by my ISP. Is there a way to achieve this without using a service like http://myexternalip.com/raw ?

相关标签:
14条回答
  • 2020-12-06 05:38

    You could very easily use an api solution for retrieving the external IP! I made a ip tracker site made for this kinda thing a few days ago! Here is a snippit of code you could use to get IP!

    async function getIp(cb) {
        let output = null;
        let promise = new Promise(resolve => {
            let http = new XMLHttpRequest();
            http.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    output = this.responseText;
                    resolve("done");
                }
            }
            http.open("GET", "https://iptrackerz.herokuapp.com/ip", true);
            http.send();
       });
      await promise;
      if (cb != undefined) {
          cb(JSON.parse(output)["ip"]);
      } else {
          return JSON.parse(output)["ip"];
      }
    }
    

    Ok, now you have the function getIp()! The way I coded it allows you to do 2 different ways of invoking it! Here they are.

    1. Asynchronous

      async function printIP() { let ip = await getIp(); document.write("Your IP is " + ip); }; printIP();

    2. Callback

      getIp(ip => { document.write("Your IP is " + ip); });

    0 讨论(0)
  • 2020-12-06 05:42

    this should work well without any external dependencies (with the exception of ipify.org):

    var https = require('https');
    
    var callback = function(err, ip){
        if(err){
            return console.log(err);
        }
        console.log('Our public IP is', ip);
        // do something here with the IP address
    };
    
    https.get({
        host: 'api.ipify.org',
    }, function(response) {
        var ip = '';
        response.on('data', function(d) {
            ip += d;
        });
        response.on('end', function() {
            if(ip){
                callback(null, ip);
            } else {
                callback('could not get public ip address :(');
            }
        });
    });
    

    You could also use https://httpbin.org

    GET https://httpbin.org/ip

    0 讨论(0)
提交回复
热议问题