SpringBoot 项目获取客户端IP地址
package tr.demo; import jakarta.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GetIPService {
//方式一 @GetMapping("/getIp") public String getIP(HttpServletRequest request){ String remoteAddr = request.getRemoteAddr(); String remoteHost = request.getRemoteHost(); System.out.println("remoteAddr="+remoteAddr); System.out.println("remoteHost="+remoteHost); return remoteAddr; }
//方式二 @GetMapping("getIp002") public String getIpAddress(HttpServletRequest request) { String ipAddress = request.getHeader("X-Forwarded-For"); if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); } System.out.println("ipAddress="+ipAddress); return ipAddress.split(",")[0]; } }