只需要在Java中获取主机名,而不是完全限定域名(FQDN)。

huangapple go评论68阅读模式
英文:

Need to get only Hostname not FQDN in java

问题

我有多个应用,托管在不同的服务器上。
所有应用程序都使用Java 8。
我尝试过使用java.net函数InetAddress.getLocalHost().getHostName()来获取主机名,但对于不同的服务器,结果不一致。
对于某些服务器,我获取到的主机名没有域名,而对于其他服务器则是完整域名。
我希望所有应用程序在相同的代码下获得一致的结果。
我希望将字符串截断保留为最后的选择。
如果Java中有某个函数仅获取主机名(不带域名),我愿使用该函数以在所有应用程序中获得一致的结果。

英文:

I have multiple applications, hosted on different servers.
All applications use java 8.
I tried java.net function InetAddress.getLocalHost().getHostName() to get hostname, it's giving inconsistent result for different servers.
For some servers, I am getting hostname without domain name and for some FQDN.
I want consistent result for all applications with same code.
I want to keep string truncation as a last option.
If some function is available in java to get only hostname(without domain name), i would like to use function to get consistent result in all applications.

答案1

得分: 1

我猜你可以尝试使用 InetAddress.getCanonicalHostName() 或 InetAddress.getName() 方法。假设在你的网络上有一个适当的名称服务运行,这两种方法应该能起作用。

关于 getCanonicalHostName() 的 JavaDocs 表示:

获取此 IP 地址的完全限定域名(FQDN)。最大努力的方法,这意味着根据底层系统配置,我们可能无法返回 FQDN。

因此,如果你想获取本地的 FQDN,通常可以调用:InetAddress.getLocalHost().getCanonicalHostName()

英文:

I guess you can try InetAddress.getCanonicalHostName() or InetAddress.getName() methods. Assuming there is a proper name service running on your net these two should do the trick.

The JavaDocs for getCanonicalHostName() says

Gets the fully qualified domain name for this IP address. Best effort method, meaning we may not be able to return the FQDN depending on the underlying system configuration.

So if you want to get your local FQDN, you can typically call: InetAddress.getLocalHost().getCanonicalHostName()

huangapple
  • 本文由 发表于 2020年10月23日 04:23:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/64490005.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定