Java如何获取主机的MAC地址?
以前,为了获取MAC地址,我们需要使用本机代码作为解决方案。在JDK1.6中,java.net.NetworkInterface类中添加了一个新方法,该方法为getHardwareAddress()。
package org.nhooo.example.network;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class MacAddress {
public static void main(String[] args) {
try {
//InetAddress地址=InetAddress.getLocalHost();
InetAddress address = InetAddress.getByName("192.168.42.26");
/*
* Get NetworkInterface for the current host and then read
* the hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
if (ni != null) {
byte[] mac = ni.getHardwareAddress();
if (mac != null) {
/*
* Extract each array of mac address and convert it
* to hexadecimal with the following format
* 08-00-27-DC-4A-9E.
*/
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s",
mac[i], (i < mac.length - 1) ? "-" : "");
}
} else {
System.out.println("Address doesn't exist or is not " +
"accessible.");
}
} else {
System.out.println("Network Interface for the specified " +
"address is not found.");
}
} catch (UnknownHostException | SocketException e) {
e.printStackTrace();
}
}
}
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短