最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node.js get client IP from http request object - Stack Overflow

programmeradmin8浏览0评论

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

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);
Share Improve this question asked Jun 25, 2013 at 22:04 FostahFostah 2,9464 gold badges56 silver badges79 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 10

It should just be req.connection.remoteAddress

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.

It should just be req.connection.remoteAddress or req.ip

Since 16.0.0 it is:

req.socket.remoteAddress

which returns a string; connection was just an alias for socket and is now deprecated.

发布评论

评论列表(0)

  1. 暂无评论