views:

48

answers:

2

Is it possible to detect the hostname used in java (even through a cname)?

I am looking for something similar to this: http://api.drupal.org/api/function/conf_path/6

In that code, drupal checks to see what domain name is accessing it in order to load the correct configuration (multi-site). If the domain doesn't match any configurations, it just goes to the default configuration.

+3  A: 

Have a look at InetAddress.getLocalHost(), followed by calling getHostName() on the returned value, which does exactly this.

Be aware that not all machines will be able to resolve a network interface which can be used for the local hostname, and that multi-homed machines run into some additional complications too. Thus if you're developing software that will need to work in a variety of situations, consider the edge cases properly as well as the happy path.

Andrzej Doyle
+1  A: 

Of course doing this causes a reverse DNS lookup for each getHostName() call.
It is a performance penalty on busy sites.
I would recommend doing getHostAddress() and later on looking up the host names.

Romain Hippeau
@Romain - this process is done at configuration time, probably *just once* when the webserver starts. I don't see how the cost of doing a reverse DNS lookup could be a concern.
Stephen C