Possible Duplicate:
compare two ip with C#
How to compare two IP? By compare I mean to tell whether IP1 is greater that IP2. Is that possible? As I see, IPAddress
does not have that functionality.
Possible Duplicate:
compare two ip with C#
How to compare two IP? By compare I mean to tell whether IP1 is greater that IP2. Is that possible? As I see, IPAddress
does not have that functionality.
edit: see the answer here for something far more elegant. Heed the warning about endian-ness, though.
Pranay Rana's answer is fundamentally broken: comparing '11.2.3.4' and '1.12.3.4' will show that they are are equal. They're clearly not.
IP addresses are essentially 32 bit integers in a particular form. You can use this fact to write a trivial function that takes the string value and gives you the integer, which is easier to compare against:
static void Main(string[] args)
{
string ip1 = "11.2.3.4";
string ip2 = "1.12.3.4";
uint ipInt1 = ipAddressToInt(ip1);
uint ipInt2 = ipAddressToInt(ip2);
Console.WriteLine(ipInt1 < ipInt2);
Console.ReadLine();
}
private static uint ipAddressToInt(string ip)
{
uint retVal;
System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse(ip);
byte[] IPBytes = ipAddress.GetAddressBytes();
retVal = (uint)IPBytes[3] << 24;
retVal += (uint)IPBytes[2] << 16;
retVal += (uint)IPBytes[1] << 8;
retVal += (uint)IPBytes[0];
return retVal;
}
Note the System.Net.IPAddress.Parse in the ipAddressToInt function. This validates the input string before working with it.
EDIT (This might work for all condition which is specified in comments )
string ip1= "1.2.3.4";
string ip2 ="5.6.7.8";
string[] ip1S = ip1.Split(new char[] {'.'});
string[] ip2S = ip2.Split(new char[] {'.'});
for(int i=0;i<4;i++)
{
if(Convert.ToInt32(ip1S[i]) > Convert.ToInt32(ip2S[i]))
{
Console.WriteLine("ip1 is higher");
break;
}
else if(Convert.ToInt32(ip2S[i]) > Convert.ToInt32(ip1S[i]))
{
Console.WriteLine("ip2 is higher");
break;
}
}
Old
you can do string comapre like this
string ip1= "1.2.3.4";
string ip2 ="5.6.7.8";
string ip1R = ip1.Replace(".","");
string ip2R = ip2.Replace(".","");
Console.WriteLine(String.Compare(ip1R ,ip2R ));
output
A negative integer str1 is less than str2.
0 str1 equals str2.
A positive integer This instance is greater than value.
-or-
1
For more change string compare on MSDN : http://msdn.microsoft.com/en-us/library/fbh501kz(v=vs.80).aspx