Get Public IP Address for node.js application

后端 未结 4 1039
天命终不由人
天命终不由人 2021-01-15 06:37

Is there any node.js module that can be used to get the public IP address of the client\'s computer making a request? I don\'t mean IPv4 or IPv6, I need the public IP like y

相关标签:
4条回答
  • 2021-01-15 06:49

    I know this old question, but now you can use http://whatismyipaddress.com/api to get IP. Just send request to bot.whatismyipaddress.com and get result.

    var http = require('http');
    http.get('http://bot.whatismyipaddress.com', function(res){
        res.setEncoding('utf8');
        res.on('data', function(chunk){
            console.log(chunk);
        });
    });
    
    0 讨论(0)
  • 2021-01-15 06:55
    var ip = (req.headers && req.headers['x-forwarded-for'])
             || req.ip 
             || req._remoteAddress 
             || (req.connection && req.connection.remoteAddress);
    
    0 讨论(0)
  • 2021-01-15 06:56

    The next line should be enough

    let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress;
    

    If you are testing locally you will see the private IP, but if you test on the cloud the IP that you will receive is the public.

    You can test it locally using ngrok

    0 讨论(0)
  • 2021-01-15 07:05

    Here's a packaged called external-ip that can do that for you va npm install external-ip:

    var externalip = require('external-ip');
    externalip(function (err, ip) {
       console.log(ip); // => 8.8.8.8
    });
    

    (sources: https://www.npmjs.org/package/external-ip, https://stackoverflow.com/a/24608249/823548)

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