[Solved] C# calculate IPs between two addresses [closed]


behold, LINQ

// don't need to know which is start or end, assuming string compare works as expected.
var addresses = new List<string>() { "192.168.10.10", "192.168.10.20" };

// convert string to a 32 bit int
Func<string, int> IpToInt = s => {
    return (
            // declare a working object
            new List<List<int>>() { 
                // chop the ip string into 4 ints
                s.Split('.').Select(x => int.Parse(x)).ToList()
            // and from the working object, return ...
        }).Select(y =>
            // ... the ip, as a 32 bit int. Note that endieness is wrong (but that doesn't matter), and it's signed.
            (y.ElementAt(0) << 24) + (y.ElementAt(1) << 16) + (y.ElementAt(2) << 8) + y.ElementAt(3)
        ).First();
};

// start range 
Enumerable.Range(0, 
    // address space is the different between the large and smaller ... which should be positive
    IpToInt(addresses.Max()) - IpToInt(addresses.Min()) + 1).ToList().ForEach(x => { 
        // use as necessary
        Console.WriteLine(
            // declare a working object 
            (new List<int>() {
                // start address added with current iteration
                IpToInt(addresses.Min()) + x 
            }).Select(n =>
                // reparse from an int back into a string
                String.Join(".", 
                    // first, convert the 32 bit int back into a list of four
                    (new List<int>(){ (n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff })
                    // and make it a string for the join
                    .Select(y => y.ToString())
                )
            ).First()
        );
});

2

solved C# calculate IPs between two addresses [closed]