如何在 Websocket API for Java Glassfish 中获取远程对等点的 IP 地址?
3 回答
See getRemoteAddr()
You will need to cast your socket Session instance to a TyrusSession, which implements the standard JSR-356 Session interface.
You might need to upgrade Tyrus, as I am not sure if the version you have supports this method. I am using Tyrus 1.7 and it works fine for me. Here is how to upgrade.
基于this answer to another question的另一种方法是获取HandshakeRequest的标头。您要查找的标头是以下任一标头。
origin: [IP Address]
x-forwarded-for: [Possibly a separate IP]
为清楚起见,这是我的设置,以及我是如何发现这一点的:
- MyMachine 上的 Wamp 2.5:6060。这承载了一个客户端 HTML 页面。
- LabMachine:6060(正常连接)和 LabMachine:6443(安全连接)上的 Wamp 2.5。这充当代理。
- MyMachine:8080(正常)和 MyMachine:8181 (SSL) 上的 GlassFish 4.0。这是终点。
我通过自己的机器、实验室机器和同事的机器连接到客户端页面。在每种情况下,WebSocket 请求的原始标头都是
但是,在每种情况下,x-forwarded-host标头都不同,与实际客户端的 IP 地址相匹配。
WebSockets
基于 HTTP 请求。因此,您可能正在扩展某个HttpServlet
或WebSocketServlet
某个地方,因此从该获取 IP 的常用方法HttpServletRequest
应该有效:
例子:
public class WebSocketsServlet extends HttpServlet {
private final WebSocketApplication app = new WebSocketApplication();
@Override
public void init(ServletConfig config) throws ServletException {
WebSocketEngine.getEngine().register(
config.getServletContext().getContextPath() + "/context", app);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("IP: " + req.getRemoteAddr());
super.doGet(req, resp);
}
}