c# calculate start and end by subnet code example

Example: c# calculate start and end by subnet

uint ip = "192.168.56.3".ConvertFromIpAddressToInteger();
 uint mask = "255.255.254.0".ConvertFromIpAddressToInteger();
 uint maskbit = "255.255.255.255".ConvertFromIpAddressToInteger();

 uint reverstmask = mask ^ maskbit;
 Console.WriteLine($"Reverse Mask :{(reverstmask).ConvertFromIntegerToIpAddress()}");
 Console.WriteLine($"Start :{(ip & mask).ConvertFromIntegerToIpAddress()}");
 Console.WriteLine($"End :{(ip | reverstmask).ConvertFromIntegerToIpAddress()}");
 public static uint ConvertFromIpAddressToInteger(this string ipAddress)
        {
            var address = IPAddress.Parse(ipAddress);
            byte[] bytes = address.GetAddressBytes();

            // flip big-endian(network order) to little-endian
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }

            return BitConverter.ToUInt32(bytes, 0);
        }

        public static string ConvertFromIntegerToIpAddress(this uint ipAddress)
        {
            byte[] bytes = BitConverter.GetBytes(ipAddress);

            // flip little-endian to big-endian(network order)
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }

            return new IPAddress(bytes).ToString();
        }

Tags:

Misc Example