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) {
// need access to IP address here
})
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) {
// need access to IP address here
})
I realize this has been answered to death, but here's a modern ES6 version I wrote that follows airbnb-base eslint standards.
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.
Note that sometimes you can get more than one IP address in
req.headers['x-forwarded-for']
. Also, anx-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 thenproxy3
.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 :Following Function has all the cases covered will help
There are two ways to get the ip address :
let ip = req.ip
let ip = req.connection.remoteAddress;
But there is a problem with above approaches.
If you are running your app behind Nginx or any proxy, every single IP addresses will be
127.0.0.1
.So, the best solution to get the ip address of user is :-
You can use request-ip, to retrieve a user's ip address. It handles quite a few of the different edge cases, some of which are mentioned in the other answers.
Disclosure: I created this module
Install:
In your app:
Hope this helps
In node 10.14 , behind nginx, you can retrieve the ip by requesting it through nginx header like this:
Then in your app.js:
After that, wherever you want it to appear: