文档

Java™ 教程
隐藏目录
网络接口参数
路径:自定义网络
课程:程序访问网络参数

网络接口参数

除了网络接口的名称和分配给它的IP地址外,您还可以访问有关网络接口的网络参数

您可以使用isUP()方法来确定网络接口是否处于“up”(运行)状态。以下方法指示网络接口的类型:

supportsMulticast()方法指示网络接口是否支持多播。当可用时,getHardwareAddress()方法返回网络接口的物理硬件地址,通常称为MAC地址。getMTU()方法返回最大传输单元(MTU),即最大的数据包大小。

以下示例在列出网络接口地址的示例基础上添加了本页描述的其他网络参数:

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("显示名称:%s\n", netint.getDisplayName());
        out.printf("名称:%s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress:%s\n", inetAddress);
        }
       
        out.printf("是否启动:%s\n", netint.isUp());
        out.printf("是否为环回接口:%s\n", netint.isLoopback());
        out.printf("是否为点对点接口:%s\n", netint.isPointToPoint());
        out.printf("是否支持多播:%s\n", netint.supportsMulticast());
        out.printf("是否为虚拟接口:%s\n", netint.isVirtual());
        out.printf("硬件地址:%s\n",
                    Arrays.toString(netint.getHardwareAddress()));
        out.printf("MTU:%s\n", netint.getMTU());
        out.printf("\n");
     }
}  

以下是示例程序的输出示例:

显示名称:bge0
名称:bge0
InetAddress:/fe80:0:0:0:203:baff:fef2:e99d%2
InetAddress:/129.156.225.59
是否启动:true
是否为环回接口:false
是否为点对点接口:false
是否支持多播:false
是否为虚拟接口:false
硬件地址:[0, 3, 4, 5, 6, 7]
MTU:1500

显示名称:lo0
名称:lo0
InetAddress:/0:0:0:0:0:0:0:1%1
InetAddress:/127.0.0.1
是否启动:true
是否为环回接口:true
是否为点对点接口:false
是否支持多播:false
是否为虚拟接口:false
硬件地址:null
MTU:8232

上一页:列出网络接口地址
下一页:处理 Cookie