Getting IP Address of the remote peer in Websocket API for Java EE 7

给你一囗甜甜゛ 提交于 2019-12-24 14:34:19

问题


How can I get the IP address of the remote peer in Websocket API for Java Glassfish ?


回答1:


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.




回答2:


Another method, based on this answer to another question, is to get the headers of the HandshakeRequest. The headers you are looking for are either of the following.

origin: [IP Address]
x-forwarded-for: [Possibly a separate IP]

Just for clarity, here's my setup, and how I discovered this:

  • Wamp 2.5 on MyMachine:6060. This hosts a client HTML page.
  • Wamp 2.5 on LabMachine:6060 (normal connections) and LabMachine:6443 (secure connections). This acts as a proxy.
  • GlassFish 4.0 on MyMachine:8080 (normal) and MyMachine:8181 (SSL). This is the endpoint.

I connected to the client page via my own machine, the lab machine, and a colleague's machine. In every case, the origin header of the WebSocket request was

http://MyMachine:6060

However, in each case the x-forwarded-host header was different, matching the IP addresses of the actual client.




回答3:


WebSockets are based on HTTP requests. Therefore you are probably extending an HttpServlet or a WebSocketServlet somewhere, so the usual way of getting the IP from the HttpServletRequest should work:

Example:

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);
    }

}


来源:https://stackoverflow.com/questions/14644629/getting-ip-address-of-the-remote-peer-in-websocket-api-for-java-ee-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!