72 lines
1.9 KiB
C#
72 lines
1.9 KiB
C#
using System.Collections.Generic;
|
|
using System.Net;
|
|
|
|
namespace AMWD.Common.Comparer
|
|
{
|
|
/// <summary>
|
|
/// Defines a method to compare two IP addresses.
|
|
/// </summary>
|
|
public class IPAddressComparer : IComparer<IPAddress>
|
|
{
|
|
/// <summary>
|
|
/// Compares two IP addresses and returns a value indicating whether one is less than,
|
|
/// equal to, or greater than the other.
|
|
/// </summary>
|
|
/// <param name="x">The first IP address.</param>
|
|
/// <param name="y">The second IP address.</param>
|
|
/// <returns>
|
|
/// A signed integer that indicates the relative values of x and y, as shown in the following table.
|
|
/// <list type="table">
|
|
/// <listheader>
|
|
/// <term>Value</term>
|
|
/// <description>Meaning</description>
|
|
/// </listheader>
|
|
/// <item>
|
|
/// <term>Less than zero</term>
|
|
/// <description>x is less than y.</description>
|
|
/// </item>
|
|
/// <item>
|
|
/// <term>Zero</term>
|
|
/// <description>x equals y.</description>
|
|
/// </item>
|
|
/// <item>
|
|
/// <term>Greater than zero</term>
|
|
/// <description>x is greater than y.</description>
|
|
/// </item>
|
|
/// </list>
|
|
/// </returns>
|
|
public int Compare(IPAddress x, IPAddress y)
|
|
{
|
|
if (x == null && y == null)
|
|
return 0;
|
|
|
|
if (x == null)
|
|
return -1;
|
|
|
|
if (y == null)
|
|
return 1;
|
|
|
|
byte[] xBytes = x.GetAddressBytes();
|
|
byte[] yBytes = y.GetAddressBytes();
|
|
|
|
// Make IPv4 and IPv6 comparable
|
|
byte[] left = xBytes.Length == 16
|
|
? xBytes
|
|
: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, xBytes[0], xBytes[1], xBytes[2], xBytes[3]];
|
|
byte[] right = yBytes.Length == 16
|
|
? yBytes
|
|
: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, yBytes[0], yBytes[1], yBytes[2], yBytes[3]];
|
|
|
|
// Compare byte for byte
|
|
for (int i = 0; i < left.Length; i++)
|
|
{
|
|
int result = left[i].CompareTo(right[i]);
|
|
if (result != 0)
|
|
return result;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
}
|
|
}
|