Reputation: 754
With the following code
InetAddress.getLocalHost().getHostAddress();
it is possible to get the hosts address. But how does the JVM find that out?
The Java API only tells you that it returns it (API Reference), but is there a DNS-Server involved, and if yes, when is it called?
And if it is only called once how is the server name saved locally?
Upvotes: 3
Views: 7195
Reputation: 70909
The actual implementation is done with JNI, in native code, so it is going to differ from platform to platform.
That said, there is no reason one needs to do DNS to lookup an ip address on a machine where the network cards are located. One can just read the ip information from the network cards.
The bad news: There is no way of knowing for certain if this will do a DNS lookup on any platform that Java runs upon, as it is native code, and the possibility of a machine doing a DNS lookup even when it is not actually necessary exists.
The good news: On my linux box, it doesn't do a DNS lookup (confirmed via wireshark), which is exactly what I would expect. If you think it's doing a lookup, there are a number of reasons why it may be doing a lookup (depending on how configurable your native bind client is) and if you install wireshark (or use a suitable network analyzer) you can quickly find out if you're looking up yourself.
Edit: note that the name lookup would be in the .getLocalHost()
portion of the chained calls, if it was to be looked-up at all.
Upvotes: 6
Reputation: 1
InetAddress.getLocalHost() doesn't do what most people think that it does. It actually returns the hostname of the machine, and the IP address associated with that hostname. This may be the address used to connect to the outside world. It may not. It just depends on how you have your system configured.
On my windowsbox it gets the machine name and the external ip address. On my linux box it returns hostname and 127.0.0.1 because I have it set so in /etc/hosts
No use of DNS server involved here.
Upvotes: 0
Reputation: 242706
InetAddress
(in particular, the result of InetAddress.getLocalHost()
) represents an IP address, and getHostAddress()
returns its textual representation, therefore it doesn't need DNS lookup.
If you need a host name, you can call getHostName()
- it may perform a reverse DNS lookup:
If this InetAddress was created with a host name, this host name will be remembered and returned; otherwise, a reverse name lookup will be performed and the result will be returned based on the system configured name lookup service. If a lookup of the name service is required, call getCanonicalHostName.
Upvotes: 0