[英]How do I access the Connection-specific DNS Suffix for each NetworkInterface in Java?
Is it possible within a Java program to access the string contained in the "Connection-specific DNS Suffix" field of a Windows machine's ipconfig /all output?
例如:
C:>ipconfig /all
以太網適配器本地連接:
Connection-specific DNS Suffix . : myexample.com <======== This string
Description . . . . . . . . . . . : Broadcom NetXtreme Gigabit Ethernet
Physical Address. . . . . . . . . : 00-30-1B-B2-77-FF
Dhcp Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
IP Address. . . . . . . . . . . . : 192.168.1.66
Subnet Mask . . . . . . . . . . . : 255.255.255.0
我知道 getDisplayName() 將返回描述(例如:Broadcom NetXtreme Gigabit Ethernet 以上),並且 getInetAddresses() 將為我提供綁定到此網絡接口的 IP 地址列表。
但是是否還有閱讀“特定於連接的 DNS 后綴”的方法?
好的,所以我想出了如何在 Windows XP 和 Windows 7 上執行此操作:
我使用了一種更復雜的方法,它適用於所有平台。
在 Windows 7、Ubuntu 12.04 和一些未知的 Linux 發行版(未知的 MacOS X 構建主機)和一台 MacBook 上測試
始終使用 Oracle JDK6。 從未與其他 VM 供應商進行過測試。
String findDnsSuffix() {
// First I get the hosts name
// This one never contains the DNS suffix (Don't know if that is the case for all VM vendors)
String hostName = InetAddress.getLocalHost().getHostName().toLowerCase();
// Alsways convert host names to lower case. Host names are
// case insensitive and I want to simplify comparison.
// Then I iterate over all network adapters that might be of interest
Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();
if (ifs == null) return ""; // Might be null
for (NetworkInterface iF : Collections.list(ifs)) { // convert enumeration to list.
if (!iF.isUp()) continue;
for (InetAddress address : Collections.list(iF.getInetAddresses())) {
if (address.isMulticastAddress()) continue;
// This name typically contains the DNS suffix. Again, at least on Oracle JDK
String name = address.getHostName().toLowerCase();
if (name.startsWith(hostName)) {
String dnsSuffix = name.substring(hostName.length());
if (dnsSuffix.startsWith(".")) return dnsSuffix;
}
}
}
return "";
}
注意:我在編輯器中寫了代碼,並沒有復制實際使用的解決方案。 它也不包含錯誤處理,例如沒有名稱的計算機,無法解析 DNS 名稱,...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.