簡體   English   中英

如何訪問 Java 中每個 NetworkInterface 的特定連接 DNS 后綴?

[英]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 上執行此操作:

  • ipconfig /all 的 output 中列出的每個網絡接口的 Connection-specific DNS Suffix 字段中包含的字符串(例如:myexample.com)可以在注冊表中找到 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interface {GUID}(其中 GUID 是感興趣的網絡接口的 GUID)作為名為 DhcpDomain 的字符串值(類型 REG_SZ)。
  • 在 Java 中訪問 windows 注冊表項並不簡單,但通過巧妙地使用反射,可以訪問在 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\ 下找到的所需網絡適配器的密鑰,然后讀取字符串數據元素名稱 Dhcp 域; 它的值是必需的字符串。
  • 有關從 Java 訪問 windows 注冊表的示例,請參見以下鏈接:

我使用了一種更復雜的方法,它適用於所有平台。

在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM