We would like to identify and display the server and port that a Java application is running on that is behind a proxy web server. This means that getServerName() and getSer
You can use ServletRequest#getLocalXXX()
methods for this.
Crunchify provides a nice example for this.
import java.net.InetAddress;
import java.net.UnknownHostException;
public class CrunchifyGetIPHostname {
public static void main(String[] args) {
InetAddress ip;
String hostname;
try {
ip = InetAddress.getLocalHost();
hostname = ip.getHostName();
System.out.println("Your current IP address : " + ip);
System.out.println("Your current Hostname : " + hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
The server hostname is part of the request, as it depends on what URL the client used to reach your host. The value you get in this way is defined on the client and does not have to be what you expect.
If you are interested in the local hostname, you can try:
String hostname = InetAddress.getLocalHost().getHostName();