Comparing two IP Addresses is something that has caused me frustration
on more than one occasion. Simply put, I always assume the default ==
operator will tell me if the addresses contained in the objects are
equal, and as always, it does not.
Using == on reference type objects will (almost all of the time) return
true if the references point to the same object. This means, comparing
two IPAddress objects using == will return true if they are the same
object, not if the addresses contained within them are the same.
However, the
IPAddress
object does override the default implementation of the Equals method,
which is what you should use when you want to compare IP Addresses.
IPAddress addr1 = IPAddress.Parse("192.168.1.100");
IPAddress addr2 = IPAddress.Parse("192.168.1.100");
Console.WriteLine(addr1 == addr2); // False
Console.WriteLine(addr1.Equals(addr2)); // True
Because my curiosity knows no bounds and it's always a good idea to know
what's behind the functions you're calling, I fired up .NET Reflector
and took a look at how Microsoft implemented the Equals function.
public override bool Equals(object comparand)
{
return this.Equals(comparand, true);
}
internal bool Equals(object comparand, bool compareScopeId)
{
if (!(comparand is IPAddress))
{
return false;
}
if (this.m_Family != ((IPAddress)comparand).m_Family)
{
return false;
}
if (this.m_Family != AddressFamily.InterNetworkV6)
{
return (((IPAddress)comparand).m_Address ==
this.m_Address);
}
for (int i = 0; i < 8; i++)
{
if (((IPAddress)comparand).m_Numbers[i] !=
this.m_Numbers[i])
{
return false;
}
}
return ((((IPAddress)comparand).m_ScopeId ==
this.m_ScopeId) || !compareScopeId);
}
The first thing they check is if you are even comparing the IPAddress
with another IPAddress. If you passed in anything else, it immediately
returns false. Next they check to see if the Address Families are the
same. This is basically the IP version the address represents -
InterNetwork (version 4) or InterNetworkV6 (version 6). Then, if the
address is not version 6, it simply compares the internal representation
of the address, which is a 64 bit integer (since an IPv4 address fits in
32 bits, I'm not sure why they chose to use a 64 bit number). If the
version is 6, it compares each part of the 128 bit address individually
(8 parts each containing a 16 bit unsigned integer).
So that's it. Just remember, when you want to compare addresses, use
.Equals. When you want to compare references, use ==.
Comments
Post a Comment