← 中文资源

简体中文版本

NetworkInterface 枚举网卡

用 NetworkInterface 枚举本机网卡:读取启用状态、MTU 与 MAC,再筛出非回环、已启用接口上的可用 IPv4 地址。

阅读英文原文

实现说明

NetworkInterface 枚举网卡可以归结为类 NetworkInterfaceDemo。 循环只出现在 for (NetworkInterface nic : Collections.list(interfaces)),它的每次迭代处理一个元素。

使用要点

  • 每一步打印都带着自己的标签:name:、up:、mtu:。

常见问题

运行「NetworkInterface 枚举网卡」会打印什么?

运行文件本身,name:、up:、mtu: 这些前缀各对应一段演示逻辑。

核心语句

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
StringBuilder hex = new StringBuilder();
byte[] mac = nic.getHardwareAddress();

代码示例

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;

public class NetworkInterfaceDemo {
    public static void main(String[] args) throws Exception {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        int usable = 0;

        for (NetworkInterface nic : Collections.list(interfaces)) {
            System.out.println("name: " + nic.getName());
            System.out.println("  up: " + nic.isUp() + " loopback: " + nic.isLoopback());
            System.out.println("  mtu: " + nic.getMTU());

            byte[] mac = nic.getHardwareAddress();
            if (mac != null) {
                StringBuilder hex = new StringBuilder();
                for (byte b : mac) {
                    hex.append(String.format("%02x", b));
                }
                System.out.println("  mac: " + hex);
            }

            // 只统计已启用、非回环接口上的 IPv4 地址
            for (InetAddress address : Collections.list(nic.getInetAddresses())) {
                if (address.getAddress().length == 4) {
                    System.out.println("  ipv4: " + address.getHostAddress());
                    if (nic.isUp() && !nic.isLoopback()) {
                        usable++;
                    }
                }
            }
        }
        System.out.println("usable ipv4 addresses: " + usable);
    }
}