本文主要讲述,如何使用 Java 代码获取用户远程访问所使用的 IP。
此方法需引进 commons-lang3-3.3.2.jar
package webtest;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
public class GetIP {
/**
* 获得用户远程地址
*/
public static String getRemoteAddr(HttpServletRequest request){
String remoteAddr = request.getHeader("X-Real-IP");
if (StringUtils.isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("X-Forwarded-For");
}else if (StringUtils.isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("Proxy-Client-IP");
}else if (StringUtils.isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("WL-Proxy-Client-IP");
}
return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
}
}