package com.lightinit.hsdatagateway.common.network;

import com.lightinit.hsdatagateway.common.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: BlackWhiteInterceptor
 * @Description: IP工具类
 * @Author: yangrui
 * @Date 2019/3/6 下午16:34
 * @Version V1.0
 **/
public class IpUtils {

	public static String getIp(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();
	}

}
