[英]Is it possible to get the IP address of an incoming websocket connection?
我的websocket服务器以这种方式运行:
ws_hdl = WebSocketHandler.new do |ws|
# here we should determine the IP address of an incoming connection
end
srv = Server.new ws_hdl
srv.listen("0.0.0.0", 8080)
是否可以获取远程主机的IP地址? 出于日志记录和安全原因,它也是必需的。
预先感谢您的任何好的建议!
我不知道您使用什么,但有了Kemal,我会这样做:
require "kemal"
ws "/" do |socket, env|
p env.request
end
Kemal.run
标头如下所示:
HTTP :: Headers {“ Host” =>“ example.com:80”,“ User-Agent” =>“ curl / 7.49.1”,“ Accept” =>“ / ”,“ Connection” =>“ Upgrade” ,“ Upgrade” =>“ websocket”,“ Origin” =>“ http://example.com:80 ”,“ Sec-WebSocket-Key” =>“ SGVsbG8sIHdvcmxkIQ ==”,“ Sec-WebSocket-Version” = >“ 13”}
然后需要在客户端前面设置像Nginx这样的代理,以将IP添加到标头: https : //stackoverflow.com/a/27458651/1597964
抱歉,我无法对此进行正确的测试,但是我认为我有解决方案。
该块具有Web套接字ws
,但也可以具有HTTP :: Context作为第二个参数。 然后,它将包含一个HTTP :: Request ,其中包含标题。 包括REMOTE_ADDR
东西。
ws_hdl = WebSocketHandler.new do |ws, context|
context.request.headers # all headers
context.request.headers["REMOTE_ADDR"]? # Should be the IP address
end
srv = Server.new ws_hdl
srv.listen("0.0.0.0", 8080)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.