方式1
直接获取IP。
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ipaddr = request.getRemoteAddr();
if(ipaddr == "0:0:0:0:0:0:0:1"){
ipaddr ="127.0.0.1";
}
System.out.println(ipaddr);
方式2
封装为工具类。
import javax.servlet.http.HttpServletRequest;
public class IPUtil {
/**
* 获取请求IP
* @param request 请求对象
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP-CLIENT-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
String OperationIp = request.getHeader("Operation-IP");
if(OperationIp != null && !"".equals(OperationIp)) {
ip = ip + ";" + OperationIp;
}
return ip;
}
}