C#计算两个地址之间的IP

时间:2017-03-22 17:18:43

标签: c# arrays

我从外部应用程序(我无法更改)收到并从中创建字符串:

string startAddress = "192.168.10.10";
string endAddress = "192.168.10.20";

我想要实现的是将它们之间的每个IP放入一个数组或类似的东西中,这样我就可以遍历它们。

这是一种管理方式的脏方法,因为我知道IP不应该离开192.168.10.0/24子网。

    string startAddress = networkRange.from;
    string endAddress = networkRange.to;

    string startAddressPartial = startAddress.Substring(startAddress.LastIndexOf('.') + 1);
    string lastAddressPartial = endAddress.Substring(endAddress.LastIndexOf('.') + 1);

    int startAddressInt = Int32.Parse(startAddressPartial);
    int lastAddressInt = Int32.Parse(lastAddressPartial);

    var networkIPArray = Enumerable.Range(startAddressInt, lastAddressInt).ToArray();

    foreach (int ip in networkIPArray)
    {
        string ipOk = "192.168.10." + ip;
        Console.WriteLine(ipOk);
    }

谢谢,

1 个答案:

答案 0 :(得分:0)

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()
        );
});