springboot获取访问者ip
时间: 2024-01-07 09:06:11 浏览: 80
springboot 获取访问者的ip地址、访问设备信息、城市地址信息的源码.zip
在Spring Boot中获取访问者的IP地址可以通过HttpServletRequest对象来实现。以下是一个示例代码:
```java
import javax.servlet.http.HttpServletRequest;
@RestController
public class MyController {
@GetMapping("/getIp")
public String getIp(HttpServletRequest request) {
String ipAddress = request.getHeader("X-Forwarded-For");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
return ipAddress;
}
}
```
上述代码中,我们通过HttpServletRequest对象的getHeader方法来获取请求头中的X-Forwarded-For字段,该字段通常包含了客户端的真实IP地址。如果X-Forwarded-For字段为空或者为unknown,则尝试获取其他可能包含IP地址的请求头字段。如果所有的请求头字段都没有获取到IP地址,则使用request.getRemoteAddr()方法获取客户端的IP地址。
阅读全文