如何在 Java 中获取系统信息

x33g5p2x  于2021-10-26 转载在 Java  
字(1.7k)|赞(0)|评价(0)|浏览(347)

在本文中,我们将使用 Java 程序获取系统详细信息。 有时我们需要在我们的项目中显示或存储系统信息。 在本例中,我们将获取系统 IP 地址、MAC 地址和主机名。

####获取IP地址

为了获取系统的 IP 地址,我们将使用 InetAddress 类,它有一个方法 public String getHostAddress() 以字符串格式返回 IP 地址。 InetAddress 类从 JDK1.0.2 开始可用
获取IP地址.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();
		}
	}
}

输出:

IP address: 192.168.0.101

获取主机名

要获取主机名 InetAddress 类,请使用另一个返回主机名的方法 public String 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();
		}
	}

}

输出:

Host Name: AtulRai-PC

获取 MAC 地址

要访问网卡详细信息,您可以使用 NetworkInterface 类,该类有一个方法 public byte[] getHardwareAddress() 返回硬件地址(通常是 MAC)并且自 JDK 1.6 起可用
获取MAC地址.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();
		}
	}
}

输出:

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

相关文章

微信公众号

最新文章

更多