Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison of IPEndPoint objects not working

Tags:

c#

I have an IPEndPoint a and b, whose IPAddress and Port are exactly the same, but the == operator is on the IPEndPoint not returning true. To make things even stranger, I tried to circumvent the problem by simply comparing the IPAddress and Port individually and it is STILL not returning true.

Has anyone encountered this before? If so, I am all ears to performant solutions. We have collections of as many as 10k IPEndPoints and are querying into them via LINQ (PLINQ pretty soon).

like image 545
Martin Mizzell Avatar asked May 06 '10 17:05

Martin Mizzell


2 Answers

Both IPEndPoint and IPAddress don't implement the == operator. By default, the == operator compares if the two objects are the same reference, not if they represent the same value.

Use the IPAddress.Equals / IPEndPoint.Equals methods instead.

like image 142
dtb Avatar answered Oct 21 '22 19:10

dtb


IPAddress does not define an overload for == however it does override Object.Equals, so your equality check should be:

public static bool AreEqual(IPEndpoint e1, IPEndpoint e2)
{
    return e1.Port == e2.Port && e1.Address.Equals(e2.Address);
}

If you are using linq, it is probably a good idea to create your own IEqualityComparer<IPEndpoint> to encapsulate this, since various linq methods take one to compare items.

like image 44
Lee Avatar answered Oct 21 '22 18:10

Lee