List Local Interfaces With NetworkInterface
Enumerate NetworkInterface instances, read hardware addresses and MTU, and filter usable IPv4 addresses excluding loopback.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.IPv4 Subnet CalculatorCalculate network and broadcast addresses, netmask, wildcard, and usable host range from an IPv4 address in CIDR notation.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.