Working with MAC and IP addresses in C #

advertisements

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.


I came up with the following example.

A method to convert IP Addresses to numbers for this purpose is easily found so I included the link inside the method I derived it from.

I am using Regular Expressions to test whether the input data matches a pattern, feel free to omit or alter as you need. (For example, Unix style MAC addresses use colons (:) instead of hyphens (-).)

To convert MAC addresses, I am just omitting the delimiter and parsing the entire string as a long int.

In my example, I am showing the numbers to which several example IP and MAC addresses convert, so you can define the upper and lower bounds and test various combinations.

using System.Globalization;
using System.Text.RegularExpressions;

string IP_UpperLimit = "192.168.1.255";
string IP_LowerLimit = "192.168.1.1";
string Mac_UpperLimit = "99-EE-EE-EE-EE-EE";
string Mac_LowerLimit = "00-00-00-00-00-00";

string IP_WithinLimit = "192.168.1.100";
string IP_OutOfBounds = "10.10.1.1";

string Mac_WithinLimit = "00-AA-11-BB-22-CC";
string Mac_OutOfBounds = "AA-11-22-33-44-55";

Console.WriteLine("IP Addresses:");
Console.WriteLine("Upper Limit: " + ConvertIP(IP_UpperLimit));
Console.WriteLine("Lower Limit: " + ConvertIP(IP_LowerLimit));
Console.WriteLine("IP_WithinLimit: " + ConvertIP(IP_WithinLimit));
Console.WriteLine("IP_OutOfBounds: " + ConvertIP(IP_OutOfBounds));
Console.WriteLine();
Console.WriteLine();

Console.WriteLine("Mac Addresses:");
Console.WriteLine("Upper Limit: " + ConvertMac(Mac_UpperLimit));
Console.WriteLine("Lower Limit: " + ConvertMac(Mac_LowerLimit));
Console.WriteLine("Mac_WithinLimit: " + ConvertMac(Mac_WithinLimit));
Console.WriteLine("Mac_OutOfBounds: " + ConvertMac(Mac_OutOfBounds));

long ConvertIP(string IP)
{
    // http://www.justin-cook.com/wp/2006/11/28/convert-an-ip-address-to-ip-number-with-php-asp-c-and-vbnet/
    Regex r = new Regex(@"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b");
    if (!r.Match(IP).Success) return 0L;
    string[] IPSplit = IP.Split('.');
    long IPNum = 0L;
    for (int i = IPSplit.Length - 1; i >= 0; i--)
        IPNum += ((Int64.Parse(IPSplit[i]) % 256) * (long)Math.Pow(256, (3 - i)));
    return IPNum;
}

long ConvertMac(string Mac)
{
    Regex r = new Regex(@"^[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}$");
    if (!r.Match(Mac).Success) return 0L;
    return Int64.Parse(Mac.Replace("-", String.Empty), NumberStyles.HexNumber);
}

So, to make use of these methods, you just perform some comparisons on the converted values:

bool IPIsGood = ConvertIP(IP_UpperLimit) >= ConvertIP(IP_Test) &&
    ConvertIP(IP_LowerLimit) <= ConvertIP(IP_Test);