2013-06-25 91 views
3

如何从http req对象获取客户端IP地址?node.js从http请求对象获取客户端IP

IE:

var util = require('util'), 
    colors = require('colors'), 
    http = require('http'), 
    httpProxy = require('../../lib/node-http-proxy'); 

// 
// Http Server with proxyRequest Handler and Latency 
// 
var proxy = new httpProxy.RoutingProxy(); 
http.createServer(function (req, res) { 
    // GET IP address here 
    // var ip = ?? 
    var buffer = httpProxy.buffer(req); 
    setTimeout(function() { 
    proxy.proxyRequest(req, res, { 
     port: 9000, 
     host: 'localhost', 
     buffer: buffer 
    }); 
    }, 200); 
}).listen(8004); 

回答

7

这应该只是req.connection.remoteAddress

5

这通常是正确的位置,以获取客户端的IP地址,但并非总是如此。如果您在node.js前使用Nginx,Apache或其他反向代理,则可能必须从req.headers获取IP地址。带有远程IP地址的标题的通用名称包括“X-Remote-IP”或“X-Originating-IP”,但不同的服务器使用不同的标题名称。

+1

代理服务器的事实标准是“X-Forwarded-For”。它支持大多数缓存代理,并且可以在nginx中配置:'proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;' –

相关问题