node.js get client IP from http request object

微信扫一扫,分享到朋友圈

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

Problem courtesy of: Fostah

Solution

It should just be req.connection.remoteAddress

Solution courtesy of: JasonM

Discussion

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.

Discussion courtesy of: Timothy Meade

This recipe can be found in it’s original form on Stack Over Flow
.

Media Picker

上一篇

从淘宝到拼多多,难逃一吸?

下一篇

你也可能喜欢

node.js get client IP from http request object

长按储存图像,分享给朋友