c#解码ip/网络号

例如1.0.1.0/24 这种格式转换成1.0.1.0 1.0.1.255

		/// <summary>
        /// 
        /// </summary>
        /// <param name="ipMask">格式为 ip/mask </param>
        /// <param name="firstIp">起始ip</param>
        /// <param name="lastIp">结束ip</param>
        public bool DecodeNetmask(string ipMask, out string firstIp, out string lastIp)
        {
            firstIp = string.Empty;
            lastIp = string.Empty;
            string[] partsIpMask = Regex.Split(ipMask, @"/");
            if (partsIpMask.Length < 2)
                return false;
            byte[] bip = IPAddress.Parse(partsIpMask[0]).GetAddressBytes();
            string mask = IntToIp(Bit2Long(Convert.ToUInt16(partsIpMask[1])));
            byte[] bsub = IPAddress.Parse(mask).GetAddressBytes();
            for (int i = 0; i < bip.Length; i++)
            {
                bip[i] = (byte)((~bsub[i]) | bip[i]);
            }
            lastIp = new IPAddress(bip).ToString();
            return true;
        }

        public static Int64 Bit2Long(UInt16 MaskBit)
        {
            //int a = 32 - MaskBit;
            //long b = 0xffffffff << a;
            //long c = b >> 0;
            return (0xffffffff << (32 - MaskBit)) >> 0;
        }

        public static string IntToIp(long ipInt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append((ipInt >> 24) & 0xFF).Append(".");
            sb.Append((ipInt >> 16) & 0xFF).Append(".");
            sb.Append((ipInt >> 8) & 0xFF).Append(".");
            sb.Append(ipInt & 0xFF);
            return sb.ToString();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值