在websocket建立连接时,获取访问客户端的真实ip
1. websocket建立连接过程
2. pom依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
3. 添加配置,握手过程中,设置真实客户端ip
import javax.servlet.http.HttpServletRequest;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.lang.reflect.Field;public class WebSocketIpConfigurator extends ServerEndpointConfig.Configurator {@Overridepublic void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {try {// 通过反射获取底层 ServletRequestField requestField = request.getClass().getDeclaredField("request");requestField.setAccessible(true);HttpServletRequest httpRequest = (HttpServletRequest) requestField.get(request);// 解析真实 IPString clientIp = IpUtils.getClientIp(httpRequest);sec.getUserProperties().put("clientIp", clientIp);} catch (Exception e) {e.printStackTrace();}}
}
class IpUtils {public static String getClientIp(HttpServletRequest request) {String ip = request.getHeader("X-Forwarded-For");if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");}if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");}if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();}// 处理多级代理(取第一个 IP)if (ip != null && ip.contains(",")) {ip = ip.split(",")[0].trim();}return ip;}
}
4. websocket建立连接时,加载配置,设置ip
5. 获取真实ip调用