Skip to main content

Determines if the specified IP address falls into a specific CIDR IP range.

        // https://stackoverflow.com/questions/9622967/how-to-see-if-an-ip-address-belongs-inside-of-a-range-of-ips-using-cidr-notation
        // true if ipAddress falls inside the CIDR range, example
        // bool result = IsInRange("10.50.30.7", "10.0.0.0/8");
        private bool IsInRange(string ipAddress, string CIDRmask)
        {
            if (CIDRmask == "0.0.0.0/0") // all
                return true;
            if (String.IsNullOrEmpty(ipAddress))
                return false;
            IPAddress ip;
            if (!IPAddress.TryParse(ipAddress, out ip))
                return false;

            string[] parts = CIDRmask.Split('/');

            int IP_addr = BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0);
            int CIDR_addr = BitConverter.ToInt32(IPAddress.Parse(parts[0]).GetAddressBytes(), 0);
            int CIDR_mask = IPAddress.HostToNetworkOrder(-1 << (32 - int.Parse(parts[1])));

            return ((IP_addr & CIDR_mask) == (CIDR_addr & CIDR_mask));
        }