package com.css.simulation.oauth.client.util;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IpUtil {

    //IP地址获取
    public static String getRemoteAddress(HttpServletRequest headers) {
        String ip = headers.getHeader("x-forwarded-for");
        if(ip != null && ip.length() != 0){
            if(ip.indexOf(",") != -1){
                ip = ip.split(",")[0];
            }
        }
        if(ip == null || ip.length() == 0){
            ip = headers.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0){
            ip = headers.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0){
            ip = headers.getHeader("HTTP_CLIENT_IP");
        }
        if(ip == null || ip.length() == 0){
            ip = headers.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if(ip == null || ip.length() == 0){
            ip = headers.getHeader("X-Real-IP");
        }
        if(ip == null || ip.length() == 0){
            ip = headers.getRemoteAddr();
        }
        if(isIpv4(ip)){
            return ip;
        }else{
            return "Illegal IP address";
        }

    }

    //IP地址验证，防止非法地址
    public static boolean isIpv4(String ipAddress) {
        String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";

        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }
}
