How can I get the IP address of the remote peer in Websocket API for Java Glassfish ?
3 Answers
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.
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
However, in each case the x-forwarded-host header was different, matching the IP addresses of the actual client.

- 1
- 1

- 283
- 5
- 17
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);
}
}

- 5,990
- 5
- 38
- 58

- 13,712
- 4
- 53
- 66
-
2this is not using java ee 7 websocket api (see jsr 356); http://java.net/projects/websocket-spec/ ; http://jcp.org/en/jsr/detail?id=356 – Pavel Bucek Feb 22 '13 at 10:17