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

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

当前回答

你可以使用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();
};

希望这能有所帮助

其他回答

首先,在项目中安装request-ip

import requestIp from 'request-ip';
const clientIp = requestIp.getClientIp(req); 
console.log(clientIp)

如果使用localhost,结果可能是::1,因为::1是真实的IP地址,是localhost的IPV6表示法。

如果你使用express.js,

app.post('/get/ip/address', function (req, res) {
      res.send(req.ip);
})

在你的请求对象中有一个属性叫socket,它是一个网络。套接字对象。净。套接字对象有一个属性remoteAddress,因此你应该能够通过这个调用得到IP:

request.socket.remoteAddress

(如果您的节点版本低于13,请使用已弃用的request.connection.remoteAddress)

EDIT

正如@juand在评论中指出的那样,如果服务器位于代理之后,获得远程IP的正确方法是request.headers['x-forwarded-for']

编辑2

在Node.js中使用express时:

如果你设置了app.set('信任代理',true),请请求。ip将返回真实ip地址,即使在代理。查看文档了解更多信息

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

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
}

请求。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.