Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js get client IP from http request object

How can I get the clients IP address from the http req object?

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);
like image 399
Fostah Avatar asked Jun 25 '13 22:06

Fostah


2 Answers

It should just be req.connection.remoteAddress

like image 99
JasonM Avatar answered Sep 28 '22 14:09

JasonM


That is usually the correct location to get the client's IP address, but not always. If you are using Nginx, Apache, or another reverse proxy in front of node.js you may have to get the IP address from req.headers. Common names for the header with the remote IP address include "X-Remote-IP" or "X-Originating-IP" but different servers use different header names.

like image 38
Timothy Meade Avatar answered Sep 28 '22 16:09

Timothy Meade