How can I determine the IP address of a given request from within a controller? For example (in express):
app.post(\'/get/ip/address\', function (req, res) {
req.ip
I was looking this up then I was like wait, I'm using express. Duh.
Following Function has all the cases covered will help
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;
}console.log("client IP is *********************" + ip);
I realize this has been answered to death, but here's a modern ES6 version I wrote that follows airbnb-base eslint standards.
const getIpAddressFromRequest = (request) => {
let ipAddr = request.connection.remoteAddress;
if (request.headers && request.headers['x-forwarded-for']) {
[ipAddr] = request.headers['x-forwarded-for'].split(',');
}
return ipAddr;
};
The X-Forwarded-For header may contain a comma-separated list of proxy IPs. The order is client,proxy1,proxy2,...,proxyN. In the real world, people implement proxies that may supply whatever they want in this header. If you are behind a load balancer or something, you can at least trust the first IP in the list is at least whatever proxy some request came through.
In node 10.14 , behind nginx, you can retrieve the ip by requesting it through nginx header like this:
proxy_set_header X-Real-IP $remote_addr;
Then in your app.js:
app.set('trust proxy', true);
After that, wherever you want it to appear:
var userIp = req.header('X-Real-IP') || req.connection.remoteAddress;
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
(req.connection.socket ? req.connection.socket.remoteAddress : null);
Note that sometimes you can get more than one IP address in req.headers['x-forwarded-for']
. Also, an x-forwarded-for
header will not always be set which may throw an error.
The general format of the field is:
x-forwarded-for: client, proxy1, proxy2, proxy3
where the value is a comma+space separated list of IP addresses, the left-most being the original client, and each successive proxy that passed the request adding the IP address where it received the request from. In this example, the request passed through proxy1
, proxy2
, and then proxy3
. proxy3
appears as remote address of the request.
This is the solution suggested by Arnav Gupta with a fix Martin has suggested below in the comments for cases when x-forwarded-for
is not set :
var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim() ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress
Simple get remote ip in nodejs:
var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;