如何使用 Node.js 中的 WebSocket (websockets/ws) 库获取客户端 IP 地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14822708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get client IP address with WebSocket (websockets/ws) library in Node.js?
提问by Grringo
I cannot find the client IP parameter on the client object.
我在客户端对象上找不到客户端 IP 参数。
回答by Chris Nolet
After a bit of messing around trying to figure out which one gives the client (web browser's) IP address, the answer is:
在尝试找出哪个给客户端(Web 浏览器的)IP 地址后,答案是:
ws._socket.remoteAddress
Or if you have access to reqvia wss.on('connection', (ws, req) => {}):
或者,如果您可以req通过wss.on('connection', (ws, req) => {})以下方式访问:
req.connection.remoteAddress;
You can use this, for example, to GeoIP locate where the user is connecting from.
例如,您可以使用它来 GeoIP 定位用户连接的位置。
Edit:
编辑:
If you're running Node behind an Nginx reverse proxy (or any other reverse proxy for that matter), you may need to use:
如果您在 Nginx 反向代理(或任何其他与此相关的反向代理)后面运行 Node,则可能需要使用:
req.headers['x-forwarded-for'] || req.connection.remoteAddress
A note on security: If your Node server is available directly as well as through the reverse proxy, you might like to check the remoteAddressbefore trusting x-forwarded-for. The remote address should be your reverse proxy's IP. There's the odd chance someone could call your service directly and spoof x-forwarded-for.
安全注意事项:如果您的 Node 服务器可直接使用,也可通过反向代理使用,则您可能希望remoteAddress在信任之前检查x-forwarded-for. 远程地址应该是您的反向代理的 IP。有人可能会直接致电您的服务并进行欺骗x-forwarded-for。
回答by tpott
Got this from printing the keys in the socket object:
通过打印套接字对象中的键得到这个:
> ws._socket.address()
{ port: 8081,
family: 2,
address: '127.0.0.1' }
> ws._socket.remoteAddress
'74.125.224.194'
> ws._socket.remotePort
41435
I don't have any documentation so I'm not sure how well this is supported across versions :/
我没有任何文档,所以我不确定跨版本的支持情况:/

