我要求获取由IPv4和IPv6范围的startIP和endIP标识的IP范围内的IP地址数。
任何人都可以指出可用于实现IP地址减法的方法吗?
IP地址的数量将是= endIP - startIP + 1
非常感谢任何回复。
答案 0 :(得分:2)
这是怎么回事?
class Program
{
static void Main(string[] args)
{
IPAddress a = new IPAddress(new byte[] { 192, 168, 11, 12 });
IPAddress b = new IPAddress(new byte[] { 192, 168, 12, 12 });
long diff = Difference(a, b);
}
private static Int64 ConvertToLong(IPAddress a)
{
byte[] addressBits = a.GetAddressBytes();
Int64 retval = 0;
for (int i = 0; i < addressBits.Length; i++)
{
retval = (retval << 8) + (int)addressBits[i];
}
return retval;
}
private static Int64 Difference(IPAddress a, IPAddress b)
{
return Math.Abs(ConvertToLong(a) - ConvertToLong(b)) - 1;
}
}
答案 1 :(得分:1)
class Program
{
static void Main(string[] args)
{
string a = "192.168.11.12";
string b = "192.168.12.12";
int diff = Math.Abs(IPToInt(a) - IPToInt(b)) + 1;
}
int IPToInt(string IP)
{
return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(IP).GetAddressBytes(), 0));
}
}