package com.yxcheng.token.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.InetAddress;

public class IpUtil {

	/**
	 * 获取用户IP
	 * @param request
	 * @return
	 */
	public static String getRequestRealIp(HttpServletRequest request) {
		String strIP = request.getHeader("X-Real-IP");
		String strTemp = request.getHeader("x-forwarded-for");
		if (StringUtil.isEmpty(strIP) && StringUtil.isNotEmpty(strTemp)) {
			String[] strArray = strTemp.split(",");
			strIP = strTemp.split(",")[strArray.length - 1];
		}
		if (strIP == null || strIP.length() == 0
				|| "unknown".equalsIgnoreCase(strIP)) {
			strIP = request.getHeader("Proxy-Client-IP");
		}
		if (strIP == null || strIP.length() == 0
				|| "unknown".equalsIgnoreCase(strIP)) {
			strIP = request.getHeader("WL-Proxy-Client-IP");
		}
		if (strIP == null || strIP.length() == 0
				|| "unknown".equalsIgnoreCase(strIP)) {
			strIP = request.getRemoteAddr();
		}
		// 如果是本地webservice转发，则使用转发的IP地址
		String strRemoteIP = request.getParameter("IP");
		if (strRemoteIP != null && strRemoteIP.length() > 0) {
			if ("127.0.0.1".equalsIgnoreCase(strIP)
					|| "localhost".equalsIgnoreCase(strIP))
				strIP = strRemoteIP;
		}
		
		return strIP;
	}
	
	/**
	 * 获取用户路由信息
	 * @param request
	 * @return
	 */
	public static String getRequestRountIp(HttpServletRequest request) {
		return request.getHeader("x-forwarded-for");
	}
	
	/**
	 * 获取url
	 * @param request
	 * @return
	 */
	public static String getRequestUrl(HttpServletRequest request) {
		StringBuffer url = request.getRequestURL();  
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();  
		return tempContextUrl;
	}

    public static boolean ping(String ipAddress) {
        int  timeOut =  5000 ;  //超时应该在5钞以上
        boolean status = false;     // 当返回值是true时，说明host是可用的，false则不可。
        try {
            status = InetAddress.getByName(ipAddress).isReachable(timeOut);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return status;
    }
	
}
