Created
October 23, 2024 12:06
-
-
Save minhtran83/9c1f68ac87a307cf2bfbb1e8244a0781 to your computer and use it in GitHub Desktop.
Java program that lists all the network interfaces and their details
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.net.*; | |
| import java.util.Enumeration; | |
| public class ListNetworkInterfaces { | |
| public static void main(String[] args) { | |
| try { | |
| // Get all network interfaces | |
| Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); | |
| // Loop through each network interface and print details | |
| while (networkInterfaces.hasMoreElements()) { | |
| NetworkInterface networkInterface = networkInterfaces.nextElement(); | |
| // Skip loopback and inactive interfaces | |
| if (networkInterface.isLoopback() || !networkInterface.isUp()) { | |
| continue; | |
| } | |
| System.out.println("Interface Name: " + networkInterface.getName()); | |
| System.out.println("Display Name: " + networkInterface.getDisplayName()); | |
| System.out.println("Hardware Address (MAC): " + getMacAddress(networkInterface)); | |
| // Print IP addresses associated with the interface | |
| Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); | |
| while (inetAddresses.hasMoreElements()) { | |
| InetAddress inetAddress = inetAddresses.nextElement(); | |
| System.out.println("IP Address: " + inetAddress.getHostAddress()); | |
| } | |
| System.out.println("----------------------------------------"); | |
| } | |
| } catch (SocketException e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| // Method to convert MAC address bytes to readable format | |
| private static String getMacAddress(NetworkInterface networkInterface) throws SocketException { | |
| byte[] macAddressBytes = networkInterface.getHardwareAddress(); | |
| if (macAddressBytes == null) { | |
| return "N/A"; | |
| } | |
| StringBuilder macAddress = new StringBuilder(); | |
| for (int i = 0; i < macAddressBytes.length; i++) { | |
| macAddress.append(String.format("%02X", macAddressBytes[i])); | |
| if (i < macAddressBytes.length - 1) { | |
| macAddress.append("-"); | |
| } | |
| } | |
| return macAddress.toString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment