package com.huimv.common.utils;

import javax.servlet.http.HttpServletRequest;
import static cn.hutool.core.net.NetUtil.isInnerIP;
/**
 * @author lichong
 */
public class IPUtil {

	private static final String UNKNOWN = "unknown";

	protected IPUtil(){

	}

	/**
	 * 获取 IP地址
	 * 使用 Nginx等反向代理软件， 则不能通过 request.getRemoteAddr()获取 IP地址
	 * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，
	 * X-Forwarded-For中第一个非 unknown的有效IP字符串，则为真实IP地址
	 *
	 * ip地址能伪造，不能百分之百确定真实ip
	 */
	public static String getIpAddr(HttpServletRequest request) {
		// 获取客户端ip地址
		String clientIp = request.getHeader("x-forwarded-for");
		if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
			clientIp = request.getHeader("Proxy-Client-IP");
		}
		if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
			clientIp = request.getHeader("WL-Proxy-Client-IP");
		}
		if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
			clientIp = request.getRemoteAddr();
		}
		/*
		 * 对于获取到多ip的情况下，找到公网ip.
		 */
		String sIP = null;
		if (clientIp != null && !clientIp.contains("unknown") && clientIp.indexOf(",") > 0) {
			String[] ipsz = clientIp.split(",");
			for (String anIpsz : ipsz) {
				if (!isInnerIP(anIpsz.trim())) {
					sIP = anIpsz.trim();
					break;
				}
			}
			/*
			 * 如果多ip都是内网ip，则取第一个ip.
			 */
			if (null == sIP) {
				sIP = ipsz[0].trim();
			}
			clientIp = sIP;
		}
		if (clientIp != null && clientIp.contains("unknown")){
			clientIp =clientIp.replaceAll("unknown,", "");
			clientIp = clientIp.trim();
		}
		if ("".equals(clientIp) || null == clientIp){
			clientIp = "127.0.0.1";
		}
		return clientIp;
	}

}
