How to see if an IP address belongs inside of a range of IPs using CIDR notation?

后端 未结 7 2050
猫巷女王i
猫巷女王i 2020-12-09 08:54

Here I have a static reference the ranges I need to check:

private static List Ip_Range = new List()
{
    \"12.144.86.0/23\",
           


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 09:38

    If you don't want/can't add another library (as the IPnetwork one) to your project and just need to deal with IPv4 CIDR ranges, here's a quick solution to your problem

    // 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)
    {
        string[] parts = CIDRmask.Split('/');
    
        int IP_addr = BitConverter.ToInt32(IPAddress.Parse(parts[0]).GetAddressBytes(), 0);
        int CIDR_addr = BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0);
        int CIDR_mask = IPAddress.HostToNetworkOrder(-1 << (32 - int.Parse(parts[1])));
    
        return ((IP_addr & CIDR_mask) == (CIDR_addr & CIDR_mask));
    }
    

    the above will allow you to quickly check if a given IPv4 address falls inside a given CIDR range; notice that the above code is barebone, it's up to you to check if a given IP (string) and CIDR range are correct before feeding them to the function (you may just use the tryparse or whatever...)

提交回复
热议问题