Comparing IPEndPoint Objects Not Working

I have IPEndPoint a and b, whose IPAddress and Port are exactly the same, but the == operator on IPEndPoint does not return true. To make things even weirder, I tried to work around this problem by simply comparing IPAddress and the port individually and STILL did not return true.

Has anyone come across this before? If so, then I am all ears to resolve. We have collections of up to 10 thousand IPEndPoints and queries to them via LINQ (PLINQ pretty soon).

+4
source share
2 answers

Both IPEndPoint and IPAddress do not implement the == operator. By default, the == operator compares whether both objects are the same reference, and not if they represent the same value.

Use IPAddress.Equals / IPEndPoint.Equals instead.

+6
source

IPAddress does not define an overload for ==, but it overrides Object.Equals, so the 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 the various linq methods use one to compare elements.

+2
source

Source: https://habr.com/ru/post/1309029/


All Articles