For example:
http.createServer(function (request, response) {
request.on("end", function () {
});
});
Using Request, how I can I find the source IP of the request?
Depending on whether the request is made by a proxy forward or direct connection the source ip address may be stored at different places. You have to check req.header['x-forwarded-for']
first and then req.connection.remoteAddress
. An example function is shown in this gist.
Here is a working example:
var http = require('http');
var getClientIp = function(req) {
var ipAddress = null;
var forwardedIpsStr = req.headers['x-forwarded-for'];
if (forwardedIpsStr) {
ipAddress = forwardedIpsStr[0];
}
if (!ipAddress) {
ipAddress = req.connection.remoteAddress;
}
return ipAddress;
};
var server = http.createServer();
server.on('request', function(req, res) {
console.log(getClientIp(req));
res.writeHead(200, {'Content-Type': 'text/plain'});
return res.end('Hello World\n');
});
server.listen(9000, 'localhost');
the getClientIp
function was taken from here with some minor changes. Note that the contents of x-forwarded-for
is an array containing proxy IPs, (read more here), so you may wish to inspect more than the first element.