Reputation: 6039
How can I get the IP address of the remote peer in Websocket API for Java Glassfish ?
Upvotes: 1
Views: 5003
Reputation: 817
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.
Upvotes: 2
Reputation:
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:
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
However, in each case the x-forwarded-host header was different, matching the IP addresses of the actual client.
Upvotes: 2
Reputation: 13857
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);
}
}
Upvotes: -2