package com.uas.report.util;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 获取IP地址类
 * </p>
 * 
 */
public class IpHelper {

	/**
	 * 获取客户端IP
	 * 
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request) {
		String ipAddress = null;
		ipAddress = request.getHeader("X-Forwarded-For");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) {
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		// window7系统下,用localhost访问时,ip会变成0:0:0:0:0:0:0:1
		if (ipAddress != null && "0:0:0:0:0:0:0:1".equals(ipAddress)) {
			ipAddress = "127.0.0.1";
		}
		return ipAddress;
	}

	/**
	 * 判断指定的ip地址是否在局域网内
	 * 
	 * @param ipAddress
	 * @return
	 */
	public static boolean isLAN(String ipAddress) {
		return Pattern.matches("^((192.168.)|(10.)|(172.16)|(127.0))+[0-9.]+$", ipAddress);
	}

}
