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

后端 未结 7 2056
猫巷女王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:47

    I use the below method to determine whether a given IP Address is a public one or private/internal:

    private bool IsInternalIpAddress(string ipAddress)
        {
            // notes: http://whatismyipaddress.com/private-ip
    
            var internalIpRanges = Enumerable
                .Range(16, 31)
                .Select(i => "172.{0}.".FormatWith(i))
                .Concat(new[] {"192.168.", "10.", "127."})
                .ToArray();
    
            return ipAddress.StartsWith(internalIpRanges);
        }
    

提交回复
热议问题