Java根据HttpServletRequest请求获取服务器的IP地址

Posted ヤBig、Bossづ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java根据HttpServletRequest请求获取服务器的IP地址相关的知识,希望对你有一定的参考价值。

  以下总结了两种根据HttpServletRequest请求获取发出请求浏览器客户端所在服务器的IP地址方法:

代码:

import javax.servlet.http.HttpServletRequest;

/**
 * 根据HttpServletRequest请求获取发出请求浏览器客户端所在服务器的IP地址
 * @author 【】
 *
 */
public class IPUtil {
	/*
	 * 第一种方法
	 */
	public String getIpAddr(HttpServletRequest request) {
		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();
		}
		return ip;
	}
	
	/*
	 * 第二种方法
	 */
	public String getIP(HttpServletRequest request) {
		String remoteAddr = request.getRemoteAddr();  
		String forwarded = request.getHeader("X-Forwarded-For");  
		String realIp = request.getHeader("X-Real-IP");  
		String ip = null;  
		if (realIp == null) {  
		    if (forwarded == null) {  
		        ip = remoteAddr;  
		    } else {  
		        ip = remoteAddr + "/" + forwarded.split(",")[0];  
		    }  
		} else {  
		    if (realIp.equals(forwarded)) {  
		        ip = realIp;  
		    } else {  
		        if(forwarded != null){  
		            forwarded = forwarded.split(",")[0];  
		        }  
		        ip = realIp + "/" + forwarded;  
		    }  
		}
		return ip;
	}
}

   注:如果在本机访问服务时(服务器和客户端都在同一台电脑上,例如用localhost访问的时候就会出现),获取的IP值会为“0:0:0:0:0:0:0:1”,这是IPV6的IP。如果本机通过localhost、127.0.0.1和本机真实地址访问时获取到的ip也有区别,把localhost换成127.0.0.1或本机真实地址就变成了IPV4,即所需的IP地址。

以上是关于Java根据HttpServletRequest请求获取服务器的IP地址的主要内容,如果未能解决你的问题,请参考以下文章

根据请求的HttpServletRequest获取ip地址工具类

springbootboot-HttpServletRequest.getInputStream() 获取post内容

httpServletRequest.setAttribute这个方法是啥意思,请详细解释下

Tomcat 8 Java 8 的 HttpServletRequest.getRemoteAddr() 为空

Java HttpServletRequest

Java HttpServletRequest中getAttribute()方法和getParameter()区别