在 Java 中获取应用程序服务器名称或 IP 和端口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1826977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Application Server name or ip and port in Java
提问by
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).
我们想识别并显示在代理 Web 服务器后面运行 Java 应用程序的服务器和端口。这意味着 getServerName() 和 getServerPort() 返回代理的服务器名称及其端口 (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 like to have is <Application Server Name>:<Application Server Port>
displayed.
我们有两个应用服务器实例在单个物理机器上运行,因此每个机器有两个活动端口,即 9080、9081 <Application Server Name>:<Application Server Port>
。显示了我想要的内容。
Any ideas? I'm a complete Java noob, sorry if this is a basic question.
有任何想法吗?我是一个完整的 Java 菜鸟,对不起,如果这是一个基本问题。
采纳答案by BalusC
You can use ServletRequest#getLocalXXX()
methods for this.
您可以ServletRequest#getLocalXXX()
为此使用方法。
ServletRequest#getLocalName()
returns local hostname.ServletRequest#getLocalAddr()
returns local IP.ServletRequest#getLocalPort()
returns local port.
ServletRequest#getLocalName()
返回本地主机名。ServletRequest#getLocalAddr()
返回本地IP。ServletRequest#getLocalPort()
返回本地端口。
回答by rsp
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.
服务器主机名是请求的一部分,因为它取决于客户端用于访问主机的 URL。您通过这种方式获得的价值是在客户端上定义的,不一定是您所期望的。
If you are interested in the local hostname, you can try:
如果您对本地主机名感兴趣,可以尝试:
String hostname = InetAddress.getLocalHost().getHostName();
回答by biniam
Crunchifyprovides a nice example for this.
Crunchify为此提供了一个很好的例子。
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();
}
}
}