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
3 Answers
Reset to default 1var 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)