PenguinProgrammer
PenguinProgrammer

Reputation: 141

Get Public IP Address for node.js application

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 you get when you go to http://www.whatismyip.com/

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 :)

Upvotes: 2

Views: 10794

Answers (3)

jose920405
jose920405

Reputation: 8049

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

Upvotes: 1

laggingreflex
laggingreflex

Reputation: 34627

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

Upvotes: 1

rae
rae

Reputation: 94

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)

Upvotes: 0

Related Questions