2011-05-26 23 views
2

在Java程序中是否可以訪問Windows計算機的ipconfig/all輸出的「連接特定的DNS後綴」字段中包含的字符串?如何訪問Java中每個NetworkInterface的連接特定DNS後綴?

如:

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()將獲得返回描述(例如:博通NetXtreme千兆以太網),並且getInetAddresses()會給我一個綁定到這個網絡接口的IP地址列表。

但也有閱讀的「連接特定的DNS後綴」的方式?

回答

3

好了,所以我想通了,如何做到這一點在Windows XP和Windows 7:包含在每個網絡 的連接特定的 DNS後綴領域:(myexample.com如)

  • 字符串在 輸出中列出接口IPCONFIG/ALL可以在 註冊表 HKEY_LOCAL_MACHINE \ SYSTEM找到\ CURRENTCONTROLSET \服務\ TCPIP \參數\接口{GUID} (其中GUID是感興趣的 網絡接口的GUID)作爲 聖環值(類型REG_SZ)名爲DhcpDomain。
  • 訪問Windows註冊表項不是直接在Java中,但通過一些巧妙地利用反射的就可以訪問下HKEY_LOCAL_MACHINE \ SYSTEM發現\ CURRENTCONTROLSET所需的網絡適配器的關鍵\服務\ TCPIP \參數\接口\,然後讀取字符串數據元素名稱爲DhcpDomain;它的值是必需的字符串。
  • 參見從Java訪問Windows註冊表 的例子 以下鏈接:
0

我用一個更復雜的方法,這在所有平臺上的工作原理。

測試在Windows 7,Ubuntu的12.04和一些未知的Linux發行版(詹金斯建立主機)和一個的MacBook(未知的MacOS X版)。

與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名稱,...

+0

這並不爲我工作(Java 8中,Windows 10)。 – jumar 2016-10-17 14:12:47