springboot 获取访公网ip
时间: 2023-06-10 18:04:18 浏览: 233
你可以使用HttpServletRequest对象来获取访问者的IP地址。在Spring Boot中,可以通过注入HttpServletRequest对象来获取IP地址,如下所示:
```
@Autowired
private HttpServletRequest request;
public String getIpAddress() {
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;
}
```
上述方法会首先尝试获取代理服务器传递的IP地址,如果无法获取,则会尝试从其他头部中获取IP地址,最后获取不到时返回请求的远程IP地址。
阅读全文