如何从控制器内确定给定请求的IP地址?例如(在快递中):

app.post('/get/ip/address', function (req, res) {
    // need access to IP address here
})

当前回答

我知道这个问题已经被回答了,但下面是我写的一个现代ES6版本,它遵循airbnb的eslint标准。

const getIpAddressFromRequest = (request) => {
  let ipAddr = request.connection.remoteAddress;

  if (request.headers && request.headers['x-forwarded-for']) {
    [ipAddr] = request.headers['x-forwarded-for'].split(',');
  }

  return ipAddr;
};

X-Forwarded-For报头可以包含以逗号分隔的代理ip列表。订单是client,proxy1,proxy2,…,proxyN。在现实世界中,人们实现的代理可以在这个报头中提供他们想要的任何东西。如果你是负载均衡器之类的,你至少可以相信列表中的第一个IP至少是某个请求通过的代理。

其他回答

你可以保持DRY,只使用支持IPv4和IPv6的node-ipware。

安装:

npm install ipware

在你的app.js或中间件中:

var getIP = require('ipware')().get_ip;
app.use(function(req, res, next) {
    var ipInfo = getIP(req);
    console.log(ipInfo);
    // { clientIp: '127.0.0.1', clientIpRoutable: false }
    next();
});

它将尽最大努力获取用户的IP地址或返回127.0.0.1,以表明它无法确定用户的IP地址。查看README文件中的高级选项。

以下函数涵盖了所有的情况,将会有所帮助

var ip;
if (req.headers['x-forwarded-for']) {
    ip = req.headers['x-forwarded-for'].split(",")[0];
} else if (req.connection && req.connection.remoteAddress) {
    ip = req.connection.remoteAddress;
} else {
    ip = req.ip;
}console.log("client IP is *********************" + ip);

要求的事情。连接已弃用node@12.12.0。使用req.connection.remoteAddress获取客户端IP可能仍然有效,但不建议使用。

幸运的是,req.socket.remoteAddress自node@0.5.10以来一直存在,是一个完美的替代品:

远程IP地址的字符串表示形式。例如,'74.125.127.100'或'2001:4860:a005::68'。如果套接字被销毁(例如,如果客户端断开连接),值可能是未定义的。

如果您使用的是快速版3。X或更大,您可以使用信任代理设置(http://expressjs.com/api.html#trust.proxy.options.table),它将遍历X -forward -for报头中的地址链,并将链中尚未配置为受信任代理的最新IP放入req对象的IP属性中。

请求。headers['x-forwarded-for'] || request.connection.remoteAddress . headers['x-forwarded-for'

如果有x-forward -for报头,则使用它,否则使用. remoteaddress属性。

The x-forwarded-for header is added to requests that pass through load balancers (or other types of proxy) set up for HTTP or HTTPS (it's also possible to add this header to requests when balancing at a TCP level using proxy protocol). This is because the request.connection.remoteAddress the property will contain the private IP address of the load balancer rather than the public IP address of the client. By using an OR statement, in the order above, you check for the existence of an x-forwarded-for header and use it if it exists otherwise use the request.connection.remoteAddress.