如何獲取我在使用Java時正在運行的計算機的域名?
對於例如,我的機器是一臺服務器,其域名可能是ec2-44-555-66-777.compute-1.amazonaws.com
使用Java獲取域名
我想InetAddress.getLocalHost().getHostName()
但是這並沒有給我起的名字上面。這給了我看起來類似的主機名ip-0A11B222
如何獲取我在使用Java時正在運行的計算機的域名?
對於例如,我的機器是一臺服務器,其域名可能是ec2-44-555-66-777.compute-1.amazonaws.com
使用Java獲取域名
我想InetAddress.getLocalHost().getHostName()
但是這並沒有給我起的名字上面。這給了我看起來類似的主機名ip-0A11B222
你真的需要域名還是IP地址足夠?如果後者,嘗試使用InetAddress.getLocalHost().getHostAddress()
是的,我真的需要域名.. – stumped 2011-05-05 00:49:15
我想你可以試試InetAddress.getCanonicalHostName()
或InetAddress.getName()
方法。假設有一個適當的名稱服務在你的網絡上運行,這兩個應該做的伎倆。
的Javadoc getCanonicalHostName()說
獲取完全合格的域名 此IP地址。盡最大努力 方法,這意味着我們可能無法通過 返回FQDN,具體取決於 底層系統配置。
今天我有同樣的問題,發現了這個非常簡單的解決方案:
System.getenv("userdomain");
它只適用於Windows – 2015-05-01 21:50:49
getCanonicalHostName爲您提供了完全合格的域名。我曾嘗試使用InetAddress.getLocalHost().getHostname()
,但它只是獲得您在命令行中看到的hostname
值,該值可能包含或不包含完全限定的名稱。
要檢查是否使用命令行(在Linux中)設置完全限定的域名,請使用hostname --fqdn
。
公共字符串getCanonicalHostName()獲取此IP地址的完全合格的域名 名。盡力而爲的方法,這意味着我們可能不能 配置返回FQDN取決於基礎系統 配置。
/** Main.java */
import java.net.InetAddress;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] ipAddress = new byte[] {(byte)127, (byte)0, (byte)0, (byte)1 };
InetAddress address = InetAddress.getByAddress(ipAddress);
String hostnameCanonical = address.getCanonicalHostName();
System.out.println(hostnameCanonical);
}
}
例摘自: http://www.java2s.com/Tutorials/Java/java.net/InetAddress/Java_InetAddress_getCanonicalHostName_.htm
你有什麼需要_for_? – 2011-05-04 23:45:23
也許這可能會幫助你一點(自己從來沒有嘗試過):http://blogs.captechconsulting.com/blog/david-tiller/accessing-the-dusty-corners-dns-java – Bart 2011-05-04 23:46:37
我剛編輯我的問題。我想我真的在尋找域名。 – stumped 2011-05-04 23:51:26