您可以通过比较字节来检查任何类型(但类型相同)的两个地址,例如 IPv6 地址:
IPAddress addr1 = IPAddress.Parse("2001:db8::1:2");
IPAddress addr2 = IPAddress.Parse("2001:db8::1:1");
var bytes1 = addr1.GetAddressBytes();
var bytes2 = addr2.GetAddressBytes();
Console.WriteLine(CompareBytes(bytes1, bytes2) > 0); // Prints: "True"
和CompareBytes
方法:
private static int CompareBytes(byte[] left, byte[] right)
{
// TODO: Null checks.
// TODO: Check that left and right have the same length.
int difference = 0;
for (int i = left.Length - 1; i >= 0; i--)
{
difference = left[i] - right[i];
if (difference != 0)
break;
}
return difference;
}
无论您的代码运行的系统的字节顺序如何,这都有效。
您可以将任何 IPv4 地址转换为等效的 IPv6 地址,如下所示:
var ipv6 = ipv4.MapToIPv6();
如果你确定你总是有 IPv4 地址,你可以只比较它们的整数值:
IPAddress addr1 = IPAddress.Parse("10.12.0.2");
IPAddress addr2 = IPAddress.Parse("10.12.0.1");
uint value1 = BitConverter.ToUInt32(addr1.GetAddressBytes(), 0);
uint value2 = BitConverter.ToUInt32(addr2.GetAddressBytes(), 0);
Console.WriteLine(value1 > value2); // Prints: "True"