Reputation: 6552
req.connection.remoteAddress, req.headers['x-forwarded-for'], req.ip, req.ips, what does it all mean?
Is there a straight forward way to simply get the IP address of the client/user-agent making the request to my site in Node.js/Express? I'm not understanding all the proxy stuff or what all the differences between all the properties of the req object. Also, I don't understand what the 'trust proxy' option is for Express.
Could someone give me a straight forward explanation to what the difference is between all of these properties, and answer how I can just simply get the client's IP?
Upvotes: 35
Views: 76487
Reputation: 7107
As other's have noted, due to the use potential use of proxies, you really should use req.ip
and NOT use the X-Forwarded-For header like so many people are recommending. As long as you properly configure a proxy as a trusted proxy, req.ip
will always return the end-user's IP address.
e.g. If you had a proxy that was connecting from 8.8.8.8, you'd do:
var express = require('express');
var app = express();
app.set('trust proxy', '8.8.8.8');
Since you trust the proxy, this would now make it so what is passed in the X-Forwarded-For header will be stored in req.ip
, but ONLY if it originates from one of the trusted proxies.
More on trust proxy can be found here.
Now, as others have noted in the comments; especially when developing locally you may get the ip
in the format of "::ffff:127.0.0.1".
To always get the IPv4 Address I have:
getClientAddress = function (req) {
return req.ip.split(":").pop();
};
Upvotes: 5
Reputation: 6459
very simple
function getClientIP(req){
return req.headers['x-forwarded-for'] || req.connection.remoteAddress;
}
Upvotes: 5
Reputation: 381
Getting the client IP is pretty straightforward:
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
console.log(ip);
Upvotes: 0
Reputation: 34337
req.ip
is the straightforward way to get the client's IP address in Express. You can see the logic it uses (which involves grabbing the first item from the array of proxy addresses req.ips
, where that array is constructed from the x-forwarded-for
headers) here.
Upvotes: 62
Reputation: 706
// Get client IP address from request object ----------------------
getClientAddress = function (req) {
return (req.headers['x-forwarded-for'] || '').split(',')[0]
|| req.connection.remoteAddress;
};
Upvotes: 21