开发者

Get Application Server name or ip and port in Java

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 getServerPort() return the server name of the proxy and its port (80).

We have two application server instances running on a single physical box and therefore have two active ports per box i.e. 9080, 9081. What I'd 开发者_如何学JAVAlike to have is <Application Server Name>:<Application Server Port> displayed.

Any ideas? I'm a complete Java noob, sorry if this is a basic question.


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();


You can use ServletRequest#getLocalXXX() methods for this.

  • ServletRequest#getLocalName() returns local hostname.
  • ServletRequest#getLocalAddr() returns local IP.
  • ServletRequest#getLocalPort() returns local port.


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();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜