0

I am trying to get client's ip address with Express js, code is as follows:

var ip;
if (req.headers['x-forwarded-for']) {
    ip = req.headers['x-forwarded-for'].split(",")[0];
} else if (req.connection && req.connection.remoteAddress) {
    ip = req.connection.remoteAddress;
} else {
    ip = req.ip;
}
ip = (ip.length < 15 ? ip : (ip.substr(0, 7) === '::ffff:' ? ip.substr(7) : undefined));


console.log('ip address',ip);

But every time I am getting localhost ip address not Public ip address, so how can I get public ip address instead of localhost ip address? can anyone help me please ?

Thanks in advance.

1
  • 1
    check server infrastructure has load balancers, proxies, etc... in front of your actual server, the above local values may return the local server, not what the actual public IP/port that the client originally connected to. Commented Nov 17, 2017 at 6:43

1 Answer 1

2

Check the last IP of the x-forwarded-for header.

For example, on aws :

the last IP address in the list is the IP address of the client http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html#x-forwarded-for

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.