检索网络interface
NetworkInterface
类没有公共构造函数。因此,您不能仅使用new
运算符来创建此类的新实例。相反,可以使用以下静态方法,以便您可以从系统检索interface详细信息:getByInetAddress()
,getByName()
和getNetworkInterfaces()
。当您已经知道特定interface的 IP 地址或名称时,将使用前两种方法。第三种方法getNetworkInterfaces()
返回计算机上interface的完整列表。
网络interface可以分层组织。 NetworkInterface
类包括与网络interface层次结构有关的两种方法getParent()
和getSubInterfaces()
。 getParent()
方法返回interface的父级NetworkInterface
。如果网络interface是子interface,则getParent()
返回非空值。 getSubInterfaces()
方法返回网络interface的所有子interface。
以下示例程序列出了计算机上所有网络interface和子interface(如果有)的名称。
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNIFs
{
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netIf : Collections.list(nets)) {
out.printf("Display name: %s\n", netIf.getDisplayName());
out.printf("Name: %s\n", netIf.getName());
displaySubInterfaces(netIf);
out.printf("\n");
}
}
static void displaySubInterfaces(NetworkInterface netIf) throws SocketException {
Enumeration<NetworkInterface> subIfs = netIf.getSubInterfaces();
for (NetworkInterface subIf : Collections.list(subIfs)) {
out.printf("\tSub Interface Display name: %s\n", subIf.getDisplayName());
out.printf("\tSub Interface Name: %s\n", subIf.getName());
}
}
}
以下是示例程序的输出示例:
Display name: bge0
Name: bge0
Sub Interface Display name: bge0:3
Sub Interface Name: bge0:3
Sub Interface Display name: bge0:2
Sub Interface Name: bge0:2
Sub Interface Display name: bge0:1
Sub Interface Name: bge0:1
Display name: lo0
Name: lo0