Node.js - 获取客户端IP时request.client._peername.address的问题

时间:2015-04-05 22:12:05

标签: node.js

我正在寻找在使用http模块建立连接时获取客户端IP地址的方法。我找到了两种方法,可能会有更多:

  1. request.connection.remoteAddress
  2. request.client._peername.address
  3. (1)似乎工作正常,但在使用(2)时我看到一些奇怪的行为。看看以下示例:

    var http = require('http');
    
    var server = http.createServer(function(request, response) {
        response.writeHead(200, {"Content-Type": "text/plain"});
    
        var clientIP1 = request.connection.remoteAddress;
        var clientIP2 = request.client._peername.address;
    
        response.write("You are (1): " + clientIP1 + "\n" + 
                       "You are (2): " + clientIP2 + "\n");
        response.end();
    }).listen(8080);
    

    上面的代码完全正常。现在让我们对它进行一些更改。

    var server = http.createServer(function(request, response) {
        response.writeHead(200, {"Content-Type": "text/plain"});
    
        // Just removed (1).
        var clientIP2 = request.client._peername.address;
    
        response.write("You are (2): " + clientIP2 + "\n");
        response.end();
    }).listen(8080);
    

    上述方法无效。这有多奇怪?它给出了以下错误:

    var clientIP2 = request.client._peername.address;
    TypeError: Cannot read property 'address' of undefined
    

    进一步的变化:

    var server = http.createServer(function(request, response) {
        response.writeHead(200, {"Content-Type": "text/plain"});
    
        var trash = request.client._peername.address;
        var clientIP2 = request.client._peername.address;
        var clientIP1 = request.connection.remoteAddress;
    
        response.write("You are (1): " + clientIP1 + "\n" + 
                       "You are (2): " + clientIP2 + "\n");
        response.end();
    }).listen(8080);
    

    以上的工作。

    所以看起来顺序很重要 - request.client._peername在执行request.connection.remoteAddress之前不会被实例化。事实上,如果您事先没有使用过(1),则不能使用(2)。

    这不是一个大问题,但有人可以解释一下这里的内部运作吗?

0 个答案:

没有答案