dimanche 5 avril 2015

Node.js - Issues with request.client._peername.address when getting Client IP

I'm looking at ways to get client's IP adress when making a connection using http module. I found two ways to do this, there may be more:



  1. request.connection.remoteAddress

  2. request.client._peername.address


(1) seems to work fine, but I see some strange behavior when using (2). Take a look at following examples:



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


Code above works perfectly fine. Now let's make some changes to it.



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


The above doesn't work. How weird is that? It gives the following error:



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


Further changes:



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


The above DOES work.


So it seems that the order is important - request.client._peername does not get instantiated before request.connection.remoteAddress is executed. In fact, you can not use (2) if you haven't used (1) beforehand.


It isn't a big issue, but could someone please explain the inner workings here?


Aucun commentaire:

Enregistrer un commentaire