Spring Websockets STOMP - get client IP address

后端 未结 3 1998
孤街浪徒
孤街浪徒 2021-02-08 21:21

Is there any way to obtain STOMP client IP address? I am intercepting inbound channel but I cannot see any way to check the ip address.

Any help appreciated.

3条回答
  •  [愿得一人]
    2021-02-08 21:49

    Below example updated to get the exact remote client ip:

    @Component
    public class IpHandshakeInterceptor implements HandshakeInterceptor {
    
       @Override
       public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map attributes) throws Exception {
        // Set ip attribute to WebSocket session
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            String ipAddress = servletRequest.getServletRequest().getHeader("X-FORWARDED-FOR");
            if (ipAddress == null) {
                ipAddress = servletRequest.getServletRequest().getRemoteAddr();
            }
            attributes.put("ip", ipAddress);
        }
        return true;
    }
    
       public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {
    }
    }
    

提交回复
热议问题