【问题标题】:Comparing Ip value for determine whether a specific range比较 Ip 值以确定是否为特定范围
【发布时间】:2013-07-30 04:02:24
【问题描述】:

有什么方法可以比较特定范围内的地址的ip地址吗?

IPAddress[] ips;
ips = Dns.GetHostAddresses("www.xyz.com");
Console.WriteLine("GetHostAddresses({0}) returns:", "www.xyz.com");
foreach (IPAddress ip in ips)
{
    Console.WriteLine("    {0}", ip);
}
Console.ReadLine();

ips 变量存储 ip 值。我想在 10.100.12.21 和 10.255.15.30 之间进行比较。 如何比较其他类型的 ips? 在比较 ip 范围之后转换为 ips 值以加倍。还是有其他想法?

【问题讨论】:

    标签: c# dns ip host


    【解决方案1】:

    使用等于:

    static void Main(string[] args)
    {
        IPAddress a, b;
    
        a = new IPAddress(new byte[] { 10, 100, 12, 21 });
        b = new IPAddress(new byte[] { 10, 100, 12, 21 });
    
        Console.WriteLine("Value is {0}", a.Equals(b));
    
        Console.ReadLine();
    }
    

    【讨论】:

    • ips = Dns.GetHostAddresses("www.xyz.com") 我想比较 10.100.12.21 和 10.255.15.30 之间的 ips 值,我需要这样 İf(ips>10.100.12.21 && 10.255 .15.30a)ips 和 a 具有相同的类型,但 IDE 不允许这种比较
    • 这样的话,你必须自己写一个,因为它并没有真正定义什么时候应该大于/小于
    【解决方案2】:

    自己的实现,试试这个:

        int[] maxIP = new int[] { 10, 255, 15, 30 };
        int[] minIP = new int[] { 10, 100, 12, 21 };
        char[] sep = new char[] { '.' };
    
        var ip = "10.100.16.21";
    
        string[] splitted = ip.Split(sep);
    
        for (int i = 0; i < splitted.Length; i++)
        {
            if (int.Parse(splitted[i]) > maxIP[i])
            {
                Console.WriteLine("IP greather than max");
                break;
            }
            else if (int.Parse(splitted[i]) < minIP[i])
            {
                Console.WriteLine("IP less than min");
                break;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      • 2011-01-09
      • 2014-04-17
      • 2015-05-20
      • 2011-06-10
      • 2022-09-23
      • 2014-03-06
      相关资源
      最近更新 更多