I have a requirement to get the number of IP addresses in an IP range identified by a startIP and an endIP both for IPv4 and IPv6 ranges.
Can anyone point to ways that can be used to achieve the subtraction of IP addresses?
开发者_开发知识库The number of IP addresses will be = endIP - startIP + 1
Any responses are highly appreciated.
How's this?
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;
}
}
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));
}
}
精彩评论