Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two ip with C#

Tags:

c#

ip

How I can compare two IP address?

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

I need some like this:

if(ip1 == ip2)
{
   //true
}
like image 977
user319854 Avatar asked Apr 27 '10 15:04

user319854


2 Answers

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))
{
    //...
}
like image 99
Lee Avatar answered Oct 23 '22 13:10

Lee


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
like image 35
JaredPar Avatar answered Oct 23 '22 12:10

JaredPar