最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get Public IP Address for node.js application - Stack Overflow

programmeradmin4浏览0评论

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

I have tried req.connection.remoteAddress; but it doesn't return the public IP. It has to be public so I can locate the city based on the IP address.

Thanks :)

Is there any node.js module that can be used to get the public IP address of the client's puter making a request? I don't mean IPv4 or IPv6, I need the public IP like you get when you go to http://www.whatismyip./

I have tried req.connection.remoteAddress; but it doesn't return the public IP. It has to be public so I can locate the city based on the IP address.

Thanks :)

Share Improve this question asked Oct 21, 2014 at 0:41 PenguinProgrammerPenguinProgrammer 1413 gold badges5 silver badges11 bronze badges 7
  • hacksparrow./node-js-get-ip-address.html – dandavis Commented Oct 21, 2014 at 1:18
  • when I used var ip = req.header('x-forwarded-for') || req.connection.remoteAddress; inside http.createServer(function(req,res) {}); it says TypeError: Object #<IningMessage> has no method 'header'. Is what you sent me in the link outdated??? – PenguinProgrammer Commented Oct 21, 2014 at 1:28
  • That way doesn't show an IP, it just gives an error – PenguinProgrammer Commented Oct 21, 2014 at 1:40
  • I keep getting the IPv4 – PenguinProgrammer Commented Oct 21, 2014 at 1:54
  • IPv4 is the public address, and it's what's shown at your link. what exactly are you expecting, can you post an example of a desired value? – dandavis Commented Oct 21, 2014 at 1:56
 |  Show 2 more ments

3 Answers 3

Reset to default 1
var ip = (req.headers && req.headers['x-forwarded-for'])
         || req.ip 
         || req._remoteAddress 
         || (req.connection && req.connection.remoteAddress);

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

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/package/external-ip, https://stackoverflow./a/24608249/823548)

发布评论

评论列表(0)

  1. 暂无评论