Simple IP within range check in C#

Works based on the fact that each IP address can be expressed to decimal number based on mathematics formula. The result decimal number is unique for given IP address.

a:b:c:d = a(256)^3 + b(256)^2 + c(256)^1 + d.
e.g.
192.168.0.1 = 192(256)^3 + 168(256)^2 + 0(256)^1 + 1 = 3232235521

Code examples

Whole code with tests are available on GitHub : GitHub

    public class IPv4Helper
    {
        public bool IsValid(string ip)
        {
            if (IPAddress.TryParse(ip, out IPAddress address))
            {
                return address.AddressFamily == AddressFamily.InterNetwork && ip != "0";
            }

            return false;
        }

        public long GetDecimalRepresentation(string ip)
        {
            if (!IsValid(ip))
            {
                throw new ArgumentException();
            }

            var ipParts = ip.Split('.');

            var decimalRepresentationOfIpAddress =
               Double.Parse(ipParts[0]) * Math.Pow(256, 3) +
               Double.Parse(ipParts[1]) * Math.Pow(256, 2) +
               Double.Parse(ipParts[2]) * 256 +
               Double.Parse(ipParts[3]);

            return (long)decimalRepresentationOfIpAddress;
        }

        public bool IsInRange(long point, long from, long to)
        {
            return point >= from && point <= to;
        }

        public bool IsInRange(string ip, string ipFrom, string ipTo)
        {
            long fromDec = GetDecimalRepresentation(ipFrom);
            long toDec = GetDecimalRepresentation(ipTo);
            long pointDec = GetDecimalRepresentation(ip);

            return IsInRange(pointDec, fromDec, toDec);
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *