简体   繁体   中英

Comparing Ip value for determine whether a specific range

Is there any method for compare ip address for address in the specific range.

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

variable stores ip value. 变量存储ip值。 I want to compare betweeen 10.100.12.21 and 10.255.15.30. How can I compare ips other type? Convert to ips value to double after that compare ip ranges. Or any other idea?

Use Equals:

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

Own implementation, Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM