方法一
public static String getIp2(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = ip.indexOf(",");
if(index != -1){
return ip.substring(0,index);
}else{
return ip;
}
}
ip = request.getHeader("X-Real-IP");
if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
return ip;
}
return request.getRemoteAddr();
}
方法二
public static String getClinetIP(HttpServletRequest request){
String ip = null;
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
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.getHeader("entrust-client-ip");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getRemoteAddr();
if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip.trim())){
InetAddress inetAddress = null;
try{
inetAddress =InetAddress.getLocalHost();
}catch (UnknownHostException e){
System.out.println("获取IP地址失败");
}
ip = inetAddress.getHostAddress();
}
}
//多级 方向代理
if (ip.indexOf(",")>0){
ip = ip.substring(0,ip.indexOf(",")).trim();
}
return ip;
}
ps:代码引用于
JAVA获取客户端IP地址-CSDN博客https://blog.csdn.net/m0_71867302/article/details/129683061?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170738691916800226562378%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=170738691916800226562378&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-2-129683061-null-null.142^v99^pc_search_result_base6&utm_term=java%E8%8E%B7%E5%8F%96%E5%AE%A2%E6%88%B7%E7%AB%AFip%E5%9C%B0%E5%9D%80&spm=1018.2226.3001.4187
问题:当项目中用到Nginx转发的时候,获取ip的时候会获取异常、
在Nginx中加入以下配置:
proxy_set_header X-Real-IP $remote_addr;文章来源:https://www.toymoban.com/news/detail-834578.html
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;文章来源地址https://www.toymoban.com/news/detail-834578.html
到了这里,关于Java 获取客户端IP的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!