List Local Interfaces With NetworkInterface

Enumerate NetworkInterface instances, read hardware addresses and MTU, and filter usable IPv4 addresses excluding loopback.

JavaConfig Management

Code

snippet
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);
    }
}

How it works

Count the class NetworkInterfaceDemo as the entire surface area of List Local Interfaces With NetworkInterface.

The one repetition in this snippet is the loop for (NetworkInterface nic : Collections.list(interfaces)).

Putting it to use

The demo output is labeled (name:, up:, mtu:), so every printed line maps back to its originating operation.

Core lines

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

Interactive Tools for This Topic

FAQ

What does List Local Interfaces With NetworkInterface print when run?
Invoke the file as-is — the `name:`, `up:`, `mtu:` prefixes identify which step printed each line.