我不完全明白我应该如何获得一个远程用户IP地址。

假设我有一个简单的请求路由,如:

app.get(/, function (req, res){
   var forwardedIpsStr = req.header('x-forwarded-for');
   var IP = '';

   if (forwardedIpsStr) {
      IP = forwardedIps = forwardedIpsStr.split(',')[0];  
   }
});

上面的方法是否正确,以获得真实的用户IP地址或有更好的方法? 那么代理呢?


当前回答

这对我来说比其他方法更有效。我的网站在CloudFlare后面,它似乎需要cf- connection -ip。

req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress

没有测试代理后面的Express,因为它没有说任何关于这个cf- connection -ip头。

其他回答

var ip = req.connection.remoteAddress;

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

添加app.set('信任代理',true) 使用要求。IP或req。Ips和往常一样

我为此写了一个包。您可以将其用作表示中间件。我的软件包发布在这里:https://www.npmjs.com/package/express-ip

您可以使用

npm i express-ip

使用

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);
});

这对我来说比其他方法更有效。我的网站在CloudFlare后面,它似乎需要cf- connection -ip。

req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress

没有测试代理后面的Express,因为它没有说任何关于这个cf- connection -ip头。

将所有的witk @kakopappa解决方案加上morgan客户端ip地址的日志记录:

morgan.token('client_ip', function getId(req) {
    return req.client_ip
});
const LOG_OUT = ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" :client_ip'
self.app.use(morgan(LOG_OUT, {
    skip: function(req, res) { // custom logging: filter status codes
        return res.statusCode < self._options.logging.statusCode;
    }
}));

// could-flare, nginx and x-real-ip support
var getIpInfoMiddleware = function(req, res, next) {
    var client_ip;
    if (req.headers['cf-connecting-ip'] && req.headers['cf-connecting-ip'].split(', ').length) {
        var first = req.headers['cf-connecting-ip'].split(', ');
        client_ip = first[0];
    } else {
        client_ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
    }
    req.client_ip = client_ip;
    next();
};
self.app.use(getIpInfoMiddleware);