IP比较

        /// <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;
        }

 

posted @ 2015-09-23 09:45  Czhipu  阅读(255)  评论(0编辑  收藏  举报