C# 计算两个地址之间的IP
我从一个无法更改的外部应用程序接收并从中创建字符串:C# 计算两个地址之间的IP,c#,arrays,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 endA
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);
}
谢谢,林克
// 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()
);
});
你说你试过什么,但没有表现出来。这里的人不会为你写代码,告诉我们你尝试了什么。你应该发布你尝试了什么。我们是来帮助你的,不是为你工作的。你不需要将它们存储在数组中来循环它们。您可以编写一个简单的枚举器类,它不需要实际存储所有中间值。在得到有意义的答案之前,您至少需要解释范围。什么是网络掩码?看看这个,想一想,我能理解代码,是的,它能按预期工作。例如,当你从192.168.10.10转到192.168.10.100时,我想这是因为它考虑了错误的最大值和最小值。@rgomez新列表{192.168.10.10,192.168.10.100}。最小值和最大值适合我