import javax.servlet.http.HttpServletRequest;
/**
* IP帮助工具
* @author jiajiayue
*/
public class IPHelper {
private static final String UNKNOWN = "unknown";
/**
* 得到用户的真实地址,如果有多个就取第一个
*
* @return
*/
public static String getIpAddr() {
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
if (request == null) {
return null;
}
String ip = request.getHeader("x-forwarded-for");
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.getRemoteAddr();
}
String[] ips = ip.split(",");
return ips[0].trim();
}
}
java获取请求IP工具类
该文章介绍了一个名为IPHelper的Java类,用于从HttpServletRequest中获取用户的实际IP地址,通过检查多个HTTP头如x-forwarded-for、Proxy-Client-IP和WL-Proxy-Client-IP,最后返回第一个非空的IP地址。
摘要由CSDN通过智能技术生成