java教程

struts2 action获取IP地址(客户端IP)

位置:首页 > java教程 > SSH教程,2018-08-11 13:17
这是struts2 action获取IP地址(客户端IP),使用时获取request,String ip = getIpAddr(ServletActionContext.getRequest());
	private 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.getHeader("HTTP_CLIENT_IP");
	     }

	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	         ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	     }

	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	         ip = request.getRemoteAddr();
	     }

	     if (ip != null && ip.indexOf(",") != -1) {
	         String[] ipWithMultiProxy = ip.split(",");

	         for(int i = 0; i < ipWithMultiProxy.length; ++i) {
	             String eachIpSegement = ipWithMultiProxy[i];
	             if (!"unknown".equalsIgnoreCase(eachIpSegement)) {
	                 ip = eachIpSegement;
	                 break;
	             }
	         }
	     }

	     return ip;
	}

TAGS:struts2 获取IP地址action获取IP地址

猜你喜欢

NewHot