Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js: how to get remote client address

I don't completely understand how I should get a remote user IP address.

Let's say I have a simple request route such as:

app.get(/, function (req, res){    var forwardedIpsStr = req.header('x-forwarded-for');    var IP = '';     if (forwardedIpsStr) {       IP = forwardedIps = forwardedIpsStr.split(',')[0];      } }); 

Is the above approach correct to get the real user IP address or is there a better way? And what about proxies?

like image 529
Erik Avatar asked Jun 01 '12 11:06

Erik


People also ask

What is the :: 1 address?

::1 is the loopback address in IPv6. Think of it as the IPv6 version of 127.0. 0.1 .


1 Answers

If you are running behind a proxy like NGiNX or what have you, only then you should check for 'x-forwarded-for':

var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress  

If the proxy isn't 'yours', I wouldn't trust the 'x-forwarded-for' header, because it can be spoofed.

like image 156
alessioalex Avatar answered Sep 17 '22 01:09

alessioalex