I'm working on a project that requires the ability to work with MAC and IP addresses. In this particular project, I have a measurement and an upper and lower limits to compare it to, i.e. the measurement must be within the range of the upper/lower limits. Both the measurement and the upper/lower limits can be MAC addresses, IP Addresses, hex, bin, etc. Is it possible to programmatically check if a MAC/IP address is within a particular range? At this point, I'm guessing I would have to convert the MAC or IP address to either hex or binary and to a comparison that way. Any other suggestions are welcome.
UPDATE: Using the info from the link alexn provided, I implemented Richard Szalay's class to check for IP Address ranges below for anyone else who needs it.
/// <summary>
/// Used for evaluating IPAddress ranges. Class courtesy of Richard Szalay's solution on http://stackoverflow.com/questions/2138706/c-how-to-check-a-input-ip-fall-in-a-specific-ip-range
/// </summary>
class IPAddressRange
{
private Byte[] _upperBytes, _lowerBytes;
private AddressFamily _addressFamily;
public IPAddressRange(IPAddress upper, IPAddress lower)
{
this._addressFamily = lower.AddressFamily;
this._upperBytes = upper.GetAddressBytes();
this._lowerBytes = lower.GetAddressBytes();
}
public Byte[] upperBytes
{
get { return _upperBytes; }
set { this._upperBytes = value; }
}
public Byte[] lowerBytes
{
get { return _lowerBytes; }
set { this._lowerBytes = value; }
}
/// <summary>
/// Determines if the IPAddress is within the range of the upper and lower limits defined in this class instance
/// </summary>
/// <param name="address">An address to check against pre-defined upper and lower limits</param>
/// <returns>True, if it's within range, false otherwise.</returns>
public bool IsInRange(IPAddress address)
{
if (address.AddressFamily != _addressFamily)
{
return false;
}
byte[] addressBytes = address.GetAddressBytes();
bool lowerBoundary = true, upperBoundary = true;
for (int i = 0; i < this.lowerBytes.Length &&
(lowerBoundary || upperBoundary); i++)
{
if ((lowerBoundary && addressBytes[i] < lowerBytes[i]) ||
(upperBoundary && addressBytes[i] > upperBytes[i]))
{
return false;
}
lowerBoundary &= (addressBytes[i] == lowerBytes[i]);
upperBoundary &= (addressBytes[i] == upperBytes[i]);
}
return true;
}
}
@JYelton - Thank you for your help, I will work on a similar class for MAC Addresses implementing the methods you outlined. I may eliminate the classes, in favor of your minimalist approach, in later iterations.