I have an application which uses dialup networking. If I connectafter starting my application, InetAddress.getLocalHost() alwaysreturns 127.0.0.1. Even if I connect before starting up,then disconnect and reconnect, the IP address I was assigned onthe first connection by PPP is returned and not the new one.Why is this happening?
In the past, I have taken some jabs at the java.net package, eitherfrom a design perspective or criticizing the JDK implementation.You’ve just run into another poorly conceived implementation detail.The InetAddress class in JDKs 1.0.2 and 1.1.x misguidedly cacheshostname lookups in a Hashtable. When a lookup is performed, thecache is checked first. If the entry is not in the cache, nativeDNS resolution is performed.
The flaw with this implementation isthat it leads to exactly the problem you’ve encountered. If thehostname to IP address mapping of the local host changes, it willnot be reported. In principle, it may be all right to do this becauseDNS servers cache mappings for set periods of time and will notinstantly reflect changes. But long-lived Java applications willbecome victims of out-dated information stored in their Hashtable.JDK 1.2 tries to improve the situation by storing cache entries ina HashMap and giving each cache entry an expiration time.
However,the fundamental problem is still there. Rather than provide anextra layer of name resolution caching in InetAddress, the JDKimplementation should rely on the native name resolution mechanisms that already have performance optimizations built in. In myopinion, you’re dealing with a bug and the only way around it isto fiddle with the JDK classes. The JDK 1.2 implementation shouldat least give you control over the caching policy and expirationtime, but it doesn’t.