【问题标题】:Working with MAC and IP addresses in C#在 C# 中使用 MAC 和 IP 地址
【发布时间】:2010-11-23 17:34:53
【问题描述】:

我正在从事一个需要能够使用 MAC 和 IP 地址的项目。在这个特定的项目中,我有一个测量值和一个上下限进行比较,即测量值必须在上限/下限的范围内。测量值和上限/下限都可以是 MAC 地址、IP 地址、十六进制、bin 等。是否可以以编程方式检查 MAC/IP 地址是否在特定范围内?在这一点上,我猜我必须将 MAC 或 IP 地址转换为十六进制或二进制,并以这种方式进行比较。欢迎任何其他建议。

更新:使用 alexn 提供的链接中的信息,我实现了 Richard Szalay 的类来检查下面的 IP 地址范围,以供其他需要它的人使用。

/// <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 - 感谢您的帮助,我将为 MAC 地址开发一个类似的类来实现您概述的方法。我可能会在以后的迭代中消除这些类,以支持您的极简主义方法。

【问题讨论】:

    标签: c# .net visual-studio programming-languages


    【解决方案1】:

    我想出了下面的例子。

    为此目的将 IP 地址转换为数字的方法很容易找到,因此我在派生它的方法中包含了链接。

    我正在使用正则表达式来测试输入数据是否与模式匹配,您可以根据需要随意省略或更改。 (例如,Unix 风格的 MAC 地址使用冒号 (:) 而不是连字符 (-)。)

    为了转换 MAC 地址,我只是省略了分隔符并将整个字符串解析为 long int。

    在我的示例中,我展示了几个示例 IP 和 MAC 地址转换成的数字,因此您可以定义上限和下限并测试各种组合。

    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);
    }
    

    因此,要使用这些方法,您只需对转换后的值进行一些比较:

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

    【讨论】:

      【解决方案2】:

      这是 Richard Szalay 在 StackOverflow 的另一个问题中开发的一个不错的课程。

      How to check a input IP fall in a specific IP range

      这是一个不错的类,允许您检查 IP 是否在指定范围内。

      是否需要同时检查 MAC 和 IP?

      【讨论】:

      • 感谢 alexn,每次测量都是 MAC 或 IP,所以我必须对两者进行比较。正如我所提到的,我正在考虑将 MAC 中的每个八位字节转换为二进制,然后以这种方式进行比较。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      相关资源
      最近更新 更多