Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
你可以访问超出分配给它的名称和 IP 地址的网络接口的网络参数
你可以使用 isUP() 方法发现网络接口是“up”(即运行)。以下方法指示网络接口类型:
isLoopback() 表示网络接口是否为环回接口。isPointToPoint() 表示接口是否为点对点接口。isVirtual() 表示接口是否为虚拟接口。supportsMulticast() 方法指示网络接口是否支持多播。getHardwareAddress() 方法返回网络接口的物理硬件地址(通常称为 MAC 地址)。getMTU() 方法返回最大传输单元(MTU),这是最大的数据包大小。
以下示例通过添加此页面中描述的其他网络参数来扩展 Listing Network Interface Addresses 中的示例:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNetsEx {
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("Up? %s\n", netint.isUp());
out.printf("Loopback? %s\n", netint.isLoopback());
out.printf("PointToPoint? %s\n", netint.isPointToPoint());
out.printf("Supports multicast? %s\n", netint.supportsMulticast());
out.printf("Virtual? %s\n", netint.isVirtual());
out.printf("Hardware address: %s\n",
Arrays.toString(netint.getHardwareAddress()));
out.printf("MTU: %s\n", netint.getMTU());
out.printf("\n");
}
}
以下是示例程序的示例输出:
Display name: bge0 Name: bge0 InetAddress: /fe80:0:0:0:203:baff:fef2:e99d%2 InetAddress: /129.156.225.59 Up? true Loopback? false PointToPoint? false Supports multicast? false Virtual? false Hardware address: [0, 3, 4, 5, 6, 7] MTU: 1500 Display name: lo0 Name: lo0 InetAddress: /0:0:0:0:0:0:0:1%1 InetAddress: /127.0.0.1 Up? true Loopback? true PointToPoint? false Supports multicast? false Virtual? false Hardware address: null MTU: 8232