Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - comparing two InetAddress which are equal fails?

I have an app that I am now developing multiplayer for. However I do not have 2 phones so I have been running a separate program on my pc (note: not the emulator!) which simulates my program and the multi-player aspects.

However on the PC I have the following code:

Packet input = inputQueue.take();

                if (clientAddress == input.getAddress())
                {
                    switch (input.type)
                    {

This works fine, Packet is simply a simple class I wrote to take info out of a Datagram packet and getAddress() returns an InetAddress. Client address is set previously in the code.

However the android app has exactly the same code, literally line for line exactly the same and this InetAddress will not equate to the other? If I take the String of the 2 InetAddress's using getHostName() or something and compare them then it DOES equal the other.

Am I doing something wrong and assuming something by thinking I can compare the two objects with an == sign? Should it be .equals() ? I thought android used the same java.net code but could there be a difference?

What IS the best way to ensure I have the same address using InetAddress's?

like image 881
iexus Avatar asked Mar 07 '26 12:03

iexus


2 Answers

It should be equals(). In Java, always compare objects using equals. == operator compares references, not content.

like image 132
MByD Avatar answered Mar 10 '26 02:03

MByD


Don't compare using ==, it checks for identical objects, not identical contents. Instead use .equals().

like image 38
nfechner Avatar answered Mar 10 '26 00:03

nfechner