比较Ip值以确定是否具体范围

时间:2013-07-30 06:26:04

标签: c# dns ip host

是否有任何方法可以比较特定范围内地址的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值转换为double。还是其他任何想法?

2 个答案:

答案 0 :(得分:0)

使用等于:

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

答案 1 :(得分:0)

自己实施,试试这个:

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