2

Simple task. I'm using the websockets server implementation by jetty, and I have to get the client IP address, but I don't know how.

Doua Beri
  • 10,612
  • 18
  • 89
  • 138

4 Answers4

5

I think it is same as it always was, grab IP from HTTPServletRequest#getRemoteAddr() like this:

public class WSServlet extends WebSocketServlet {

    ...
    ...

    @Override
    public WebSocket doWebSocketConnect(HttpServletRequest req, String str) {
        System.out.println("IP: "+ req.getRemoteAddr());
        ...
    }
}
Nishant
  • 54,584
  • 13
  • 112
  • 127
2

If you are using org.eclipse.jetty.websocket.api.Session I would go for:

session.getRemoteAddress().getAddress().getHostAddress();
MonoThreaded
  • 11,429
  • 12
  • 71
  • 102
1

Without WebServletSocket:

public static String getClientIp(Session session) {
        String ip = session.getUserProperties().get("javax.websocket.endpoint.remoteAddress").toString();
        int i1 = ip.indexOf("/");
        int i2 = ip.indexOf(":");
        return ip.substring(i1 + 1, i2);
    }
pheiss
  • 29
  • 3
  • 1
    This does not work with IPv6 addresses. Better is InetSocketAddress ip = (InetSocketAddress)session.getUserProperties().get("javax.websocket.endpoint.remoteAddress"); return ip.getAddress().getHostAddress(); – Horcrux7 Nov 24 '16 at 12:54
0

If you need it for authentification purposes, you can get it like this:

This is just an example:

@Override
public boolean canPublish(BayeuxServer server, ServerSession client,
                          ServerChannel channel, ServerMessage messsage) {
  //
  BayeuxContext context=server.getContext();
  System.out.println(context.getRemoteAddress());
  return true;
}

Please keep in mind that getRemoteAddress returns an InetSocketAddress string. So you also have the port, which looks something like this:

/79.111.111.22:49372
Alex
  • 1