码迷,mamicode.com
首页 > 其他好文 > 详细

IP比较

时间:2015-09-23 10:29:15      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

        /// <summary>  
        /// 检测用户ip是否在指定的ip段中  
        /// </summary>  
        /// <param name="ip">用户ip</param>  
        /// <param name="begip">起始ip</param>  
        /// <param name="endip">结束ip</param>  
        /// <returns></returns>  
        protected bool isinip(string ip, string begip, string endip)
        {
            string[] inip, begipint, endipint = new string[4];
            inip = ip.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries);
            begipint = begip.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries);
            endipint = endip.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < 4; i++)
            {
                int intip = int.Parse(inip[i]);
                int intbegip = int.Parse(begipint[i]);
                int intendip = int.Parse(endipint[i]);

                if (intip < intbegip || intip > intendip)
                    return false;
                else if (intip > intbegip || intip < intendip)
                    return true;
            }
            return true;
        }


        static public uint IPAddressToLong(string IPAddr)
        {
            System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddr);
            byte[] byteIP = oIP.GetAddressBytes();
            uint ip = (uint)byteIP[3] << 24;
            ip += (uint)byteIP[2] << 16;
            ip += (uint)byteIP[1] << 8;
            ip += (uint)byteIP[0];
            return ip;
        }
        static private uint IPAddressToLongBackwards(string IPAddr)
        {
            System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddr);
            byte[] byteIP = oIP.GetAddressBytes();
            uint ip = (uint)byteIP[0] << 24;
            ip += (uint)byteIP[1] << 16;
            ip += (uint)byteIP[2] << 8;
            ip += (uint)byteIP[3];
            return ip;
        }

        public static long IP2Long(string ip)
        {
            string[] ipBytes;
            double num = 0;
            if (!string.IsNullOrEmpty(ip))
            {
                ipBytes = ip.Split(.);
                for (int i = ipBytes.Length - 1; i >= 0; i--)
                {
                    num += ((int.Parse(ipBytes[i]) % 256) * Math.Pow(256, (3 - i)));
                }
            }
            return (long)num;
        }

 

IP比较

标签:

原文地址:http://www.cnblogs.com/Czhipu/p/4829366.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!