如何使用 Node.js 中的 WebSocket (websockets/ws) 库获取客户端 IP 地址? [英] How to get client IP address with WebSocket (websockets/ws) library in Node.js?

查看:22
本文介绍了如何使用 Node.js 中的 WebSocket (websockets/ws) 库获取客户端 IP 地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在客户端对象上找不到客户端 IP 参数.

I cannot find the client IP parameter on the client object.

推荐答案

经过一番折腾,试图找出哪个给客户端(Web 浏览器)的 IP 地址后,答案是:

After a bit of messing around trying to figure out which one gives the client (web browser's) IP address, the answer is:

ws._socket.remoteAddress

或者如果您可以通过 wss.on('connection', (ws, req) => {}) 访问 req:

Or if you have access to req via wss.on('connection', (ws, req) => {}):

req.socket.remoteAddress

例如,您可以使用它来通过 GeoIP 定位用户连接的来源.

You can use this, for example, to GeoIP locate where the user is connecting from.

如果您在 Nginx 反向代理(或任何其他与此相关的反向代理)后面运行 Node,则可能需要使用:

If you're running Node behind an Nginx reverse proxy (or any other reverse proxy for that matter), you may need to use:

req.headers['x-forwarded-for'] || req.connection.remoteAddress

安全注意事项:如果您的 Node 服务器既可以直接使用,也可以通过反向代理使用,您可能希望在信任 x-forwarded-for 之前检查 remoteAddress.远程地址应该是您的反向代理的 IP.有人可能会直接调用您的服务并欺骗 x-forwarded-for.

这篇关于如何使用 Node.js 中的 WebSocket (websockets/ws) 库获取客户端 IP 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆