Express.js:如何获取远程客户端地址

406

我不完全理解如何获取远程用户的IP地址。

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

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

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

上述方法获取真实用户IP地址是否正确,还有更好的方法吗?代理服务器如何处理?


3
按照**这里的说明,使用node-ipware**如何? - Avid Coder
如果您无法获取req.hostname,例如'example.com':https://dev59.com/Gmkw5IYBdhLWcg3wBmGA#37824880 - zhi.yang
1
可能是重复的问题:如何在Node中确定用户的IP地址 - Dan Dascalescu
1
我决定检查之前提到的 node-ipware(很久以前), 但现在已经被弃用了。建议使用 @fullerstack/nax-ipware 作为替代品,但其许可证明源代码是“专有和机密的”。 - contrebis
16个回答

4

在我的情况下,类似于这个解决方案,我最终采用了以下x-forwarded-for方法:

let ip = (req.headers['x-forwarded-for'] || '').split(',')[0];

x-forwarded-for 头部会一直添加来自源头到最终目标服务器的 IP 路由,因此如果需要检索源客户端的 IP,则这将是数组的第一项


2

var ip = req.connection.remoteAddress;

将获取到的ip地址进行分割,取第四个元素。


从这个输出中,我们可以得到IP地址:::ffff:XXX.XX.XX.XX - Bhulawat Ajay
3
如果出现正常的IP地址如127.0.0.1,我认为 ip = ip.split(':').pop(); 在这种情况下会更好。这段代码仍然可以提供IP地址,同时也会使代码更容易理解。 - 9me

2

这对我来说比其他方法都更好用。我的网站在CloudFlare后面,似乎需要使用cf-connecting-ip

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

由于它没有提到cf-connecting-ip头,因此没有测试Express代理后面的设置


1
头部对象包含你所需的一切,只需执行以下操作:
var ip = req.headers['x-forwarded-for'].split(',')[0];

1
使用云平台、nginx和x-real-ip支持。
var user_ip;

    if(req.headers['cf-connecting-ip'] && req.headers['cf-connecting-ip'].split(', ').length) {
      let first = req.headers['cf-connecting-ip'].split(', ');
      user_ip = first[0];
    } else {
      let user_ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
    }

-1
将所有内容与@kakopappa的解决方案以及客户端IP地址的morgan日志记录放在一起:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接