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

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

当前回答

var ip = req.headers['x-forwarded-for'] ||
     req.socket.remoteAddress ||
     null;

请注意,有时您可以在req.headers['x-forwarded-for']中获得多个IP地址。此外,并不总是设置x-forward -for报头,这可能会抛出错误。

该字段的一般格式为:

x-forward -for: client, proxy1, proxy2, proxy3

其中的值是一个逗号+空格分隔的IP地址列表,最左边是原始客户端,每个传递请求的后续代理添加接收请求的IP地址。在本例中,请求通过proxy1、proxy2和proxy3传递。Proxy3显示为请求的远程地址。

这是Arnav Gupta提出的解决方案,Martin在下面的评论中为未设置x-forward -for的情况提出了修复建议:

var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim() || 
         req.socket.remoteAddress

使用现代JS的建议:

仅在设置时处理x-forward -for,如果设置了,则取第一个地址 其他参数使用可选链接(?.)

const parseIp = (req) =>
    req.headers['x-forwarded-for']?.split(',').shift()
    || req.socket?.remoteAddress

console.log(parseIp(req))
// => 127.0.0.1

其他回答

函数getCallerIP(请求){ Var IP = request。标题(“x-forwarded-for”)| | request.connection.remoteAddress | | request.socket.remoteAddress | | request.connection.socket.remoteAddress; IP = IP .split(',')[0]; IP = IP .split(':').slice(-1);//如果IP以“::ffff:146.xxx.xxx.xxx”格式返回 返回的ip; }

对于我使用kubernetes ingress (NGINX):

req.headers['x-original-forwarded-for']

在Node.js中非常有效

这里有很多很棒的观点,但没有一个是全面的,所以这里是我最终使用的:

function getIP(req) {
  // req.connection is deprecated
  const conRemoteAddress = req.connection?.remoteAddress
  // req.socket is said to replace req.connection
  const sockRemoteAddress = req.socket?.remoteAddress
  // some platforms use x-real-ip
  const xRealIP = req.headers['x-real-ip']
  // most proxies use x-forwarded-for
  const xForwardedForIP = (() => {
    const xForwardedFor = req.headers['x-forwarded-for']
    if (xForwardedFor) {
      // The x-forwarded-for header can contain a comma-separated list of
      // IP's. Further, some are comma separated with spaces, so whitespace is trimmed.
      const ips = xForwardedFor.split(',').map(ip => ip.trim())
      return ips[0]
    }
  })()
  // prefer x-forwarded-for and fallback to the others
  return xForwardedForIP || xRealIP || sockRemoteAddress || conRemoteAddress
}

你可以使用request-ip来获取用户的ip地址。它处理了很多不同的边界情况,其中一些在其他答案中提到过。

披露:我创建了这个模块

安装:

npm install request-ip

在你的应用中:

var requestIp = require('request-ip');

// inside middleware handler
var ipMiddleware = function(req, res, next) {
    var clientIp = requestIp.getClientIp(req); // on localhost > 127.0.0.1
    next();
};

希望这能有所帮助

你可以像这样快速获取用户Ip

req.ip

在这个例子中,我们获取了用户的Ip,然后用req.ip把它发回给用户

app.get('/', (req, res)=> { 
    res.send({ ip : req.ip})
    
})