7

Can I get remote IP address inside @OnOpen method of @ServletEndpoint class? I tried follow this Accessing HttpSession from HttpServletRequest in a Web Socket @SocketEndpoint but as in Websocket - httpSession returns null it doesn't work.

Anyway I only need clients IP address.

Community
  • 1
  • 1
ZdeenaP
  • 73
  • 1
  • 1
  • 3

3 Answers3

4

The JSR-356 Websocket specification does not expose client IP address.

You may try one of the 2 hacks descibed in this response: JSR-356 WebSockets with Tomcat - How to limit connections within single IP address?

Community
  • 1
  • 1
Benjamin
  • 1,816
  • 13
  • 21
4

Added: Works for Jetty implementation and it's not a common solution. Thanks to Benjamin !

Don't know if you still need it. I myself directly get the IP from the socket Session.

@OnOpen
public void onWebSocketConnect(Session session) {
    System.Out.println(session.getUserProperties().get("javax.websocket.endpoint.remoteAddress"))
}

Then I get /127.0.0.1:57045

Aere Xu
  • 269
  • 1
  • 3
  • 11
  • 2
    The `javax.websocket.endpoint.remoteAddress` property is not part of the JSR-356 (see http://jcp.org/en/jsr/detail?id=356). I suspect this is something specific to Jetty's websocket implementation. For example, I tried on WildFly 8.2, which uses Undertow, and the `session.getUserProperties()` returns a Map with no predefined values... So this solution is not portable and may not work on all websocket implementations. – Benjamin Jan 11 '17 at 08:42
  • @Benjamin I agree. I was using Jetty implementation but found no answer at that time. Then I tried most of its API to find a solution for me and post the answer here. I haven't try any other implementation. – Aere Xu Feb 07 '17 at 09:01
  • For Tomcat there is a workaround with reflection: https://stackoverflow.com/a/32629586/166524 – lapo Jan 19 '18 at 10:27
  • 1
    @AereXu this does not work if Jetty is behind NGINX. – Alpha2k Feb 26 '18 at 22:12
0

Usually the client will be some Javascript code in a web page delivered by your web application.

Have the client first fetch a servlet, that calls req.getRemoteAddr() and so on Servlet returns this data. Javascript then can send the data as @PathParam to the @ServerEndpoint.

weberjn
  • 1,840
  • 20
  • 24