我正在为windows编写一个程序,列出所有网络适配器并停用所有选定的程序。 我知道如何使用netsh修改网络适配器,但问题是我无法从NetworkInterface类中获取相关信息。
NetworkInterface类的方法是getName()和getDisplayName(),但它们似乎只生成不相关的数据。
我直接从oracle中获取了这个例子:
http://docs.oracle.com/javase/tutorial/networking/nifs/listing.html
public class ListNets {
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
}
此示例生成此类输出:
Display name: Intel(R) Ethernet Connection (2) I219-V Name: eth4 InetAddress: /10.0.0.4 InetAddress: /fe80:0:0:0:cc75:ed6:3089:bd61%eth4
但是我无法使用此信息,因为netsh需要适配器的名称,Ethernet 1
不是Intel(R) Ethernet Connection (2) I219-V
或eth4
。
在我看来,getName()应返回操作系统特定的名称,并在操作系统本身中使用。是否有可能用其他标准java类来检索适配器的真实名称?
目前我的唯一解决方案是getmac /fo csv /v
来获取正确的信息并进行解析。由于我不想编写自己的包装器来访问c ++函数GetAdaptersAddresses
,因为我需要学习它。
答案 0 :(得分:0)
我刚刚回答了similar question并遇到了这个问题。因此,对任何想知道的人来说,tl; dr都是this comment来自枚举JVM中接口名称的本机实现:
/*
* Windows implementation of the java.net.NetworkInterface native methods.
* This module provides the implementations of getAll, getByName, getByIndex,
* and getByAddress.
*
* Interfaces and addresses are enumerated using the IP helper routines
* GetIfTable, GetIfAddrTable resp. These routines are available on Windows
* 98, NT SP+4, 2000, and XP. They are also available on Windows 95 if
* IE is upgraded to 5.x.
*
* Windows does not have any standard for device names so we are forced
* to use our own convention which is based on the normal Unix naming
* convention ("lo" for the loopback, eth0, eth1, .. for ethernet devices,
* tr0, tr1, .. for token ring, and so on). This convention gives us
* consistency across multiple Windows editions and also consistency with
* Solaris/Linux device names. Note that we always enumerate in index
* order and this ensures consistent device number across invocations.
*/
是的,由于Windows 95是一件事,它已经被故意破坏了。