我想获得以太网卡的MAC(用于产品密钥)
我尝试使用这种解决方案并在这里搜索,问题是当所有网络断开连接(以太网和wifi)时,它返回空MAC地址.
我宁愿得到以太网的地址,即使它已断开连接.
谢谢!!
public static void main(String[] args)
{
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
System.out.println("The mac Address of this machine is :" + ip.getHostAddress());
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
System.out.print("The mac address is : ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++){
sb.append(String.format("%02X%s", mac[i],(i< mac.length - 1)?"-":""));
}
System.out.println(sb.toString());
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (SocketException e) {
e.printStackTrace();
}
}
}
最佳答案 使用InetAddress会绑定您查看IP地址列表.如果没有,因为接口都已断开连接,那么就无法遍历这些接口.
您应该尝试使用NetworkInterface类.
public class MacAddressTest
{
public static void main(String[] args) throws Exception
{
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements())
{
NetworkInterface nif = interfaces.nextElement();
byte[] lBytes = nif.getHardwareAddress();
StringBuffer lStringBuffer = new StringBuffer();
if (lBytes != null)
{
for (byte b : lBytes)
{
lStringBuffer.append(String.format("%1$02X ", new Byte(b)));
}
}
System.out.println(lStringBuffer);
}
}
}