如何从这种格式算出该范围内的所有IP地址?
213.159.160.0-213.159.191.255
84.44.115.72-84.44.115.79
我找到了84.44.115.1/23
格式的示例,但没有上述格式的示例。
答案 0 :(得分:1)
那这样的事情呢?:
public static IPAddress[] GetAddresses(string rangeString)
{
var match = Regex.Match(rangeString, @"(?<ip1>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})-(?<ip2>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})");
if (!match.Success || !IPAddress.TryParse(match.Groups["ip1"].Value, out IPAddress ip1) || !IPAddress.TryParse(match.Groups["ip2"].Value, out IPAddress ip2))
{
throw new ArgumentException("Range invalid.");
}
return GetAddresses(ip1, ip2);
}
public static IPAddress[] GetAddresses(IPAddress startAddress, IPAddress endAddress)
{
var startNumber = IPToNumber(startAddress);
var endNumber = IPToNumber(endAddress);
var addresses = new List<IPAddress>();
for (uint i = startNumber; i <= endNumber; ++i)
{
addresses.Add(NumberToIP(i));
}
return addresses.ToArray();
}
private static UInt32 IPToNumber(IPAddress ip)
{
var bytes = ip.GetAddressBytes();
UInt32 result = 0;
for (int i = 0; i < bytes.Length; ++i)
{
result *= 255;
result += bytes[i];
}
return result;
}
private static IPAddress NumberToIP(UInt32 number)
{
var bytes = new Stack<byte>(4);
while (number > 0)
{
bytes.Push((byte)(number % 255));
number /= 255;
}
return new IPAddress(bytes.ToArray());
}
它将起始和地址转换为UInt32
值,并进行数字循环,将索引转换回IPAddress对象。
我不确定您是否需要解析范围字符串,因此我将其作为单独的方法添加到顶部。如果确实需要,可以将这些方法合并为一个,否则可以不理会它。