InetAddress.getHostName(), unexpected behavior when no hostname exists
Prag
pragprogger at gmail.com
Sun Nov 28 22:44:09 UTC 2021
When an InetAddress instance is created from an IP-address, and
getHostName() is called, and the IP-address doesn't have a hostname, then
getHostName() will unexpectedly return the IP-address itself as hostname.
This strange gehavior isn't documented:
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/net/InetAddress.html#getHostName()
The documentation does mention that if the operation isn't allowed by the
security manager, then it will cause this behavior. But even when no
security manager is set, if no hostname exists, it will return the
IP-address itself. This behavior differs from command line tools like
nslookup, which do say that no domain exists.
In my opinion, it should either throw an UnknownHostException, return null
or return an Optional<String>.
The underlying code that is called by getHostName(), is a private interface
NameService, which has getHostByAddr(), which does work as expected: it
throws an UnknownHostException if the IP-address doesn't have a hostname.
But getHostName() swallows this exception, and then returns the IP-address
instead, which is wrong behavior.
IMO even when a security manager blocks the request, it should never return
the IP-address as hostname, but simply re-throw the SecurityException from
NameService.getHostByAddr().
You can see the problem causing code here:
https://github.com/openjdk/jdk/blob/jdk-17+35/src/java.base/share/classes/java/net/InetAddress.java#L697
JDK 18 has a modified getHostname(), but it still has this unexpected
behavior.
https://github.com/openjdk/jdk/blob/jdk-18+25/src/java.base/share/classes/java/net/InetAddress.java
Here are some examples of people who run into this unexpected behavior:
https://stackoverflow.com/questions/1899288/cannot-get-hostname-from-gethostname
https://stackoverflow.com/questions/34436938/why-is-javas-inetaddress-gethostname-not-giving-me-the-hosts-name
https://stackoverflow.com/questions/24458460/inetaddress-gethostname-returning-ipaddres-on-android
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/net-dev/attachments/20211128/f1b2d95c/attachment.htm>
More information about the net-dev
mailing list