亚马逊ELB后面带有node-js的远程IP地址
我在弹性负载均衡器(elb)后面的实例存储亚马逊机器上有一个节点应用程序。然而,远程IP地址似乎总是相同的。我使用此代码在节点中获取客户端的 IP 地址(通过 connect/express):
req.socket.remoteAddress
我没有从节点文档中获得任何其他信息。有什么提示吗?
I have a node application on an instance-store amazon machine behind the elastic load balancer (elb). However, the remote IP adress seems to always be the same. I used this code to get the client's IP address in node (via connect/express):
req.socket.remoteAddress
I didn't get anything else from the node documentation. Any hint?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是如果您使用快递的解决方案:
根据文档,您可以为您的express实例启用
信任代理
然后req.ip
将填充正确的 IP 地址。这是一个例子:
Here's a solution in case you are using express:
According to the documentation, you can enable
trust proxy
for your express instance and thenreq.ip
will be populated with the correct ip address.Here's an example:
答案对我有用,谢谢。但你可以尝试:
The answer worked for me, thanks. But you may just try:
您收到 ELB 实例的 IP,并且需要从标头中获取 x-forwarded-for 值。由于我不是 Node.js 专家,因此我在 http://forum.webfaction.com/ 找到了这段代码viewtopic.php?id=4500
示例:
Your receiving the IP of the ELB instance and you'll need to get the x-forwarded-for value from the headers. Since I'm not a node.js guru, I found this code at http://forum.webfaction.com/viewtopic.php?id=4500
Example:
这里选择的正确答案是危险的,因为 AWS ELB 按预期切换顺序: https ://github.com/koajs/koa/issues/1094#issuecomment-345861282
Express、koa等通常采取最左边的项目,而 ELB 使其成为最右边的项目
(express docs):
The selected correct answer here is dangerous, because AWS ELBs switch the order as expected: https://github.com/koajs/koa/issues/1094#issuecomment-345861282
Express, koa, etc. typically take the left-most item, while ELB makes it the right-most item
(express docs):
如果 express.js 正在使用:
而不是
因为
app.enable('trust proxy')
使用 x-forwarded-for 标头中最左边的 ip,并且因此只需手动提供 x-forwarded-for 标头即可轻松欺骗。而
app.set('trust proxy', 2)
指定了从 x-forwarded-for 标头从右到左计数的跳数。即,如果有一个 AWS 负载均衡器,则计数的正确数字将是 2 以上,因为每个新的跃点 ip 都会添加到 x-forwarded-for 标头的末尾。如果您使用其他东西,请执行类似的操作。只需获取
req.headers['x-forwarded-for']
,用逗号分割,然后从右到左计算跳数,直到不排除负载均衡器 ip。In case if express.js is in use:
Instead of
Because the
app.enable('trust proxy')
uses the leftmost ip from the x-forwarded-for header and so can be easily spoofed by just providing x-forwarded-for header manually.While the
app.set('trust proxy', 2)
has the number of hops specified that being counted from right to left of the x-forwarded-for header. I.e. if there is an AWS load balancer than 2 will be the right number to count because each new hop ip is added to the end of the x-forwarded-for header.If you're using something else then do the similar way. Just get the
req.headers['x-forwarded-for']
, split by coma and then count hops from right to left until load balancer ip is not excluded.