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

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

当前回答

如果你正在使用Graphql-Yoga,你可以使用以下函数:

const getRequestIpAddress = (request) => { const requestIpAddress = request.request。headers['X-Forwarded-For'] || request.request.connection.remoteAddress . headers['X-Forwarded-For' if (!requestIpAddress)返回null const ipv4 = new RegExp(“(?:(?:25(0 - 5)| 2[0 - 9][0 - 4]|[01]?[0 - 9][0 - 9]?)\){3}(?:25(0 - 5)| 2[0 - 9][0 - 4]|[01]?[0 - 9][0 - 9]?)”) const [ipAddress] = requesttipaddress .match(ipv4) 返回ipAddress }

其他回答

Var ipaddress = (req。标题(“x-forwarded-for”)| | req.connection.remoteAddress | | req.socket.remoteAddress | | req.connection.socket.remoteAddress) .split (", ") [0];

在你的请求对象中有一个属性叫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地址,即使在代理。查看文档了解更多信息

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

在shell中,只需curl https://api.ipify.org

所以,让我们观察一下,把它移植到node.js!

Curl是一个从网站获取数据的应用程序,我们传递网站“https://api.ipify.org”作为参数。我们可以使用节点取回来替换curl!

我们从网站上获得的数据是我们的IP地址,这是一种获取你的IP地址的东西。

总结一下:

const fetch = require('node-fetch');

fetch('https://api.ipify.org')
  .then(response => {/* whatever */})
  .catch(err => {/* whatever */})

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