using System;
using System.Web;
namespace CommonForNate
{
    public class CheckIP
    {
        public CheckIP()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
        #region 获取真实IP
        /// <summary>
        /// 获取真实IP
        /// </summary>
        /// <returns>返回IP字符串</returns>
        public static string GetRealIP()
        {
            string ip;
            try
            {
                HttpRequest request = HttpContext.Current.Request;
                if (request.ServerVariables["HTTP_VIA"] != null)
                {
                    ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
                }
                else
                {
                    ip = request.UserHostAddress;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return ip;
        }
        #endregion
        #region 将IP地址格式化为整数型 IpToInt(string ip)
        /// <summary> 
        /// 将IP地址格式化为整数型 
        /// </summary> 
        /// <param name="ip"></param> 
        /// <returns></returns> 
        public static long IpToInt(string ip)
        {
            char[] dot = new char[] { '.' };
            string[] ipArr = ip.Split(dot);
            if (ipArr.Length == 3)
                ip = ip + ".0";
            ipArr = ip.Split(dot);
            long ip_Int = 0;
            long p1 = long.Parse(ipArr[0]) * 256 * 256 * 256;
            long p2 = long.Parse(ipArr[1]) * 256 * 256;
            long p3 = long.Parse(ipArr[2]) * 256;
            long p4 = long.Parse(ipArr[3]);
            ip_Int = p1 + p2 + p3 + p4;
            return ip_Int;
        }
        #endregion
        #region 判断IP是否为内网IP
        /// <summary>
        /// 获取真实IP
        /// </summary>
        /// <returns>返回IP字符串</returns>
        public static bool DoCheckIP(string GetIP)
        {
            bool ok = false;
            //允许的IP地址范围:ipcheck
            string[,] ipcheck = new string[,] { { "222.18.0.1", "222.18.255.255" }, { "172.0.0.0", "172.255.255.255" }, { "192.168.0.1", "192.168.255.255" }, { "10.0.0.1", "10.255.255.255" }, { "210.41.0.0", "210.41.255.255" }, { "125.71.1.1", "125.71.255.255" } };
            long intIP = IpToInt(GetIP);
            for (int i = 0; i < ipcheck.GetLength(0); i++)
            {
                if (intIP < IpToInt(ipcheck[i, 0]) || intIP > IpToInt(ipcheck[i, 1]))
                    return false;
            }
            return true;
        }
        #endregion
    }
}
posted on 2012-04-10 10:21  kitea  阅读(109)  评论(0)    收藏  举报