获取真实IP的工具类

来源:互联网 发布:机械公差查询软件 编辑:程序博客网 时间:2024/06/04 23:28
 package com.easyssh.framework.utils;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IpUtils
{
    public IpUtils()
    {
    }
    public static String getClientIp(HttpServletRequest request)
    {
        String ip = request.getHeader("x-forwarded-for");
        if(LOG.isDebugEnabled())
            LOG.debug("x-forwarded-for = {}", ip);
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP");
            if(LOG.isDebugEnabled())
                LOG.debug("Proxy-Client-IP = {}", ip);
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP");
            if(LOG.isDebugEnabled())
                LOG.debug("WL-Proxy-Client-IP = {}", ip);
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
            if(LOG.isDebugEnabled())
                LOG.debug("RemoteAddr-IP = {}", ip);
        }
        if(StringUtils.isNotEmpty(ip))
            ip = ip.split(",")[0];
        return ip;
    }
    public static boolean ipMatch(String ip, String ips[])
    {
        if(ips == null || ips.length == 0)
            throw new IllegalArgumentException("ips is null or emtpy");
        boolean f = false;
        List list = new ArrayList();
        for(int i = 0; i < ips.length; i++)
            list.add(ips[i].replaceAll("//*", "////d+").replaceAll("//.", "////."));
        Iterator i$ = list.iterator();
        do
        {
            if(!i$.hasNext())
                break;
            String e = (String)i$.next();
            if(!ip.matches(e))
                continue;
            f = true;
            break;
        } while(true);
        return f;
    }
    protected static final Logger LOG = LoggerFactory.getLogger(com/easyssh/framework/utils/IpUtils);
}
原创粉丝点击