你如何获得客户的IP地址? (Spring WebFlux WebSocket)

How do you get Client's IP address? (Spring WebFlux WebSocket)

正如标题所说,你如何获得连接的详细信息。有没有办法通过WebSocketSession获取?我觉得我错过了什么...

我需要一种方法来禁止不良用户的 IP 地址,而且我想在地图上显示所有在线用户(如地图上的一个点)。稍后我不需要帮助我需要帮助获取客户端的 IP 地址。

我正在使用 Spring 的 WebFlux WebSocket。

编辑:我创建了一个功能请求:https://jira.spring.io/browse/SWF-1728

WebSocketSession 有一个名为 getRemoteAddress() 的方法,您可以使用它的任何实现来获取远程地址。

您可以使用 HttpServletRequest 查找 IP 地址,例如

 String remoteHost = request.getRemoteHost();
    String remoteAddr = request.getRemoteAddr();
    if (remoteAddr.equals("0:0:0:0:0:0:0:1")) {
        InetAddress localip = java.net.InetAddress.getLocalHost();
        remoteAddr = localip.getHostAddress();
        remoteHost = localip.getHostName();
    }

基于 Servlet 的 WebSocketSession 对象确实提供了该信息。这似乎是反应式风格所缺少的。

您应该创建一个 Spring Framework issue to request this as an enhancement

我做到了

public Mono<ServerResponse> hello(ServerRequest request) {
    String remoteAddr = request.remoteAddress().get().getAddress().getHostAddress());

    return null;
}