compare two ip with C#

后端 未结 6 1301
夕颜
夕颜 2021-01-08 01:31

How I can compare two IP address?

string ip1 = \"123.123.123.123\";
string ip2 = \"124.124.124.124\";

I need some like this:



        
相关标签:
6条回答
  • 2021-01-08 01:41

    You can use this class to compare IpAddress :

    http://www.codeproject.com/Articles/26550/Extending-the-IPAddress-object-to-allow-relative-c

    0 讨论(0)
  • 2021-01-08 01:43

    It seems System.Net.IPAddress defines it's own Equals override so this should work:

    IPAddress ip1 = IPAddress.Parse("123.123.123.123");
    IPAddress ip2 = IPAddress.Parse("124.124.124.124");
    
    if(ip1.Equals(ip2))
    {
        //...
    }
    
    0 讨论(0)
  • 2021-01-08 01:44

    The type IPAddress in the BCL supports equality and can be used for this purpose.

    public static bool IsSameIPAddress(string ip1, string ip2) {
      IPAddress leftIP = IPAddress.Parse(ip1);
      IPAddress rightIP = IPAddress.Parse(ip2);
      return leftIP.Equals(rightIP);
    }
    

    Several people have wondered why a straight string comparison is not sufficient. The reason why is that an IP address can be legally represented in both base 10 and hexidecimal notation. So the same IP address can have more than 1 string representation.

    For example

    var left = "0x5.0x5.0x5.0x5";
    var right = "5.5.5.5";
    IsSameIPAddress(left,right); // true
    left == right; // false
    
    0 讨论(0)
  • 2021-01-08 01:46

    The IPAddress class (System.Net) has an overridden Equals method that will compare the addresses, not the object instances, which is what you want. String comparison here may be dangerous since it is possible for IP addresses to have more than one string representation. http://msdn.microsoft.com/en-us/library/system.net.ipaddress.equals%28v=VS.71%29.aspx

    IPAddress.Parse(ip1).Equals(IPAddress.Parse(ip2))
    
    0 讨论(0)
  • 2021-01-08 01:51

    Check out Equals method on System.Net.IPAddress

    0 讨论(0)
  • 2021-01-08 01:51
    IPAddress addr1 = IPAddress.Parse(ip1);
    IPAddress addr2 = IPAddress.Parse(ip2);
    
    return (addr1.Equals(addr2));
    
    0 讨论(0)
提交回复
热议问题