问题描述
|
在Java程序中是否可以访问Windows计算机ipconfig / all输出的“特定于连接的DNS后缀”字段中包含的字符串?
例如:
C:> ipconfig /全部
以太网适配器本地连接:
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千兆以太网),而getInetAddresses()会给我一个绑定到此网络接口的IP地址的列表。
但是,还有其他方法可以读取“特定于连接的DNS后缀”吗?
解决方法
好的,所以我弄清楚了如何在Windows XP和Windows 7上执行此操作:
字符串(例如:myexample.com)
包含在特定于连接中
每个网络的DNS后缀字段
输出中列出的接口
ipconfig / all可以在
注册表在
HKEY_LOCAL_MACHINE \\ SYSTEM \\ CurrentControlSet \\ Services \\ Tcpip \\ Parameters \\ Interfaces {GUID}
(其中GUID是
感兴趣的网络接口)
名为DhcpDomain的字符串值(类型REG_SZ)。
在Java中,访问Windows注册表项并不简单,但是通过巧妙地使用反射,可以访问在HKEY_LOCAL_MACHINE \\ SYSTEM \\ CurrentControlSet \\ Services \\ Tcpip \\ Parameters \\ Interfaces下找到的所需网络适配器的键。 \\,然后读取名称为DhcpDomain的字符串数据元素;它的值是必需的字符串。
有关示例,请参见以下链接
Windows注册表的访问
从Java:
http://www.rgagnon.com/javadetails/java-0630.html
http://lenkite.blogspot.com/2008/05/access-windows-registry-using-java.html
,我使用了一种更为复杂的方法,该方法适用于所有平台。
在Windows 7,Ubuntu 12.04和一些未知的Linux发行版(Jenkins构建主机)和一台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名称,...