1

如何在 Websocket API for Java Glassfish 中获取远程对等点的 IP 地址?

4

3 回答 3

2

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.

于 2014-08-04T01:59:35.610 回答
2

基于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 请求的原始标头都是

http://MyMachine:6060

但是,在每种情况下,x-forwarded-host标头都不同,与实际客户端的 IP 地址相匹配。

于 2015-02-18T10:30:42.010 回答
-2

WebSockets基于 HTTP 请求。因此,您可能正在扩展某个HttpServletWebSocketServlet某个地方,因此从该获取 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);
    }

}
于 2013-02-01T11:50:58.040 回答