How to get System Information in Java


In this article, we will get the system details using Java program. Sometimes we need we need to display or store the system information in our project. In this example, we are going to get the system IP address, MAC address and Hostname.

Get IP Address

To get the IP address of system we are going to use InetAddress class which has a method public String getHostAddress() that return the IP address in a string format. InetAddress class is available since JDK1.0.2

GetIPAddress.java
package org.websparrow;

import java.net.InetAddress;

public class GetIPAddress {
	public static void main(String[] args) {
		try {
			
			InetAddress inetAddress = InetAddress.getLocalHost();

			String ipAddress = inetAddress.getHostAddress();
			System.out.println("IP address: " + ipAddress);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output:

IP address: 192.168.0.101

Get Host Name

To get the Host Name InetAddress class have another method public String getHostName() that return the Hostname.

GetHostName.java
package org.websparrow;

import java.net.InetAddress;

public class GetHostName {
	public static void main(String[] args) {
		try {

			InetAddress inetAddress = InetAddress.getLocalHost();

			String hostName = inetAddress.getHostName();
			System.out.println("Host Name: " + hostName);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Output:

Host Name: AtulRai-PC

Get MAC Address

To access the network card details you can use NetworkInterface class which have a method public byte[] getHardwareAddress() return the hardware address (usually MAC) and available since JDK 1.6

GetMACAddress.java
package org.websparrow;

import java.net.InetAddress;
import java.net.NetworkInterface;

public class GetMACAddress {
	public static void main(String[] args) {
		try {
			
			InetAddress inetAddress = InetAddress.getLocalHost();
			NetworkInterface networkInterface = NetworkInterface.getByInetAddress(inetAddress);
			
			byte[] macAddress = networkInterface.getHardwareAddress();
			StringBuilder stringBuilder = new StringBuilder();
			
			for (int i = 0; i < macAddress.length; i++) {
				
				stringBuilder.append(String.format("%02X%s", macAddress[i], (i < macAddress.length - 1) ? "-" : ""));
			}
			
			System.out.println("MAC address : " + stringBuilder.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output:

MAC address : 08-ED-B9-51-52-5B

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.