Express.js: how to get remote client address

2019-01-03 07:50发布

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?

10条回答
小情绪 Triste *
2楼-- · 2019-01-03 08:34

While the answer from @alessioalex works, there's another way as stated in the Express behind proxies section of Express - guide.

  1. Add app.enable('trust proxy') to your express initialization code.
  2. When you want to get the ip of the remote client, use req.ip or req.ips in the usual way (as if there isn't a reverse proxy)

More options for 'trust proxy' are available if you need something more sophisticated than trusting everything passed through in x-forwarded-for header, and your proxy doesn't remove preexisting x-forwarded-for header from untrusted sources. See the linked guide for more details.

NOTE: req.connection.remoteAddress won't work with my solution.

查看更多
唯我独甜
3楼-- · 2019-01-03 08:34

According to Express behind proxies, req.ip has taken into account reverse proxy if you have configured trust proxy properly. Therefore it's better than req.connection.remoteAddress which is obtained from network layer and unaware of proxy.

查看更多
疯言疯语
4楼-- · 2019-01-03 08:36

Just use this express middleware https://www.npmjs.com/package/express-ip

You can install the module using

npm i express-ip

Usage

const express = require('express');
const app = express();
const expressip = require('express-ip');
app.use(expressip().getIpInfoMiddleware);

app.get('/', function (req, res) {
    console.log(req.ipInfo);
});
查看更多
Rolldiameter
5楼-- · 2019-01-03 08:43

var ip = req.connection.remoteAddress;

ip = ip.split(':')[3];

查看更多
登录 后发表回答