A small Caveat on using java.net.InetAddress
InetAddress is very handy to represent an Internet Protocol (IP) address but one caveat is the usage of basic equals() and toString() methods.
Scenario:Let’s see you’re calling InetAddress.getLocalHost() toget a local IP ip1 and then there’s another InetAddress object called ip2 and you’re asked to see whether they represent the same IP. What my intuition tell me the right way to do it is:
https://gist.github.com/zhonglowu/5c919517e5d581310953dc1b56c12ff0
I noticed sometimes even they represent the same IP, the above method still returns false . Later, I found out why from the JavaDoc:
“
public String toString()
Converts this IP address to a
String. The string returned is of the form: hostname / literal IP address. If the host name is unresolved, no reverse name service lookup is performed. The hostname part will be represented by an empty string.”
It basically indicates that toString() is not deterministic and the return value depends on whether the hostname can be resolved or not.
Also, it turns out that to compare two InetAddress objects, using equals() method is good enough. It would compares the hiddlen IP address instead of checking whether they’re the same object reference.