Get Application Server name or ip and port in Java

后端 未结 3 442
粉色の甜心
粉色の甜心 2020-12-15 01:15

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

相关标签:
3条回答
  • 2020-12-15 01:43

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

    • ServletRequest#getLocalName() returns local hostname.
    • ServletRequest#getLocalAddr() returns local IP.
    • ServletRequest#getLocalPort() returns local port.
    0 讨论(0)
  • 2020-12-15 01:53

    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 讨论(0)
  • 2020-12-15 02:00

    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();
    
    0 讨论(0)
提交回复
热议问题