jedu
jedu

Reputation: 1331

How to get public IP address of client sending the request using Nodejs express?

I want to get the public IP address of the client using Nodejs express. I searched for the question online which lead me to use this:

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

However, in my console I get

::ffff:192.168.1.2

which is my local IP address not the public IP address

Upvotes: 3

Views: 12748

Answers (3)

Rendy
Rendy

Reputation: 1

I have tried, if you want to get a public ip on express like this:

var ip = req.ip
    || req.connection.remoteAddress
    || req.socket.remoteAddress
    || req.connection.socket.remoteAddress;

console.log(ip);

Upvotes: 0

Tomas
Tomas

Reputation: 1694

Your code is actually correct. There are two reasons why it is not working for you:

  1. req.connection.remoteAddress shows the ip address of requester. In your case, your node is listening at private ip address so the only foreign ip address which can contact your server is another computer working on the same private ip range. Using public ip address for your node instance would fix the problem.

  2. req.headers['x-forwarded-for'] can work only if there is a header present in the request. Usually this is the case when you have a proxy (some http server - nginx, apache...) listening on public network and relaying communication to the node server which is accessible only from private network. And this proxy will add x-forwarded-for header to the request with ip address of the original client. In your case you don't have a proxy or the proxy is not configured to do it. Without more information is not possible to say exactly.

Upvotes: 8

Thomas Aumaitre
Thomas Aumaitre

Reputation: 807

You must use ip module

npm install ip

Upvotes: -4

Related Questions