7

我有一个在 Nginx 后面运行的 Express 应用程序,所以当我尝试获取用户的 IP 时,我总是得到127.0.0.1而不是真实的,这是由 Nginx 在X-Real-IP标题中设置的。我如何得到这个标题?有没有办法通过对象获得它socket

代码基本上是这样的:

io.sockets.on( 'connection', function( socket ) {

    var ip = /* ??? */;

    /* do something with the IP…

       … some stuff …

     */
});
4

1 回答 1

25

在 NGINX 或其他代理后面运行时获取 IP:

var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;

或用于 Socket.IO

client.handshake.headers['x-forwarded-for'] || client.handshake.address.address;

来自:http ://www.hacksparrow.com/node-js-get-ip-address.html

于 2012-11-26T20:58:56.043 回答