我想获取我的MAC地址。我用下面的代码来做到这一点。但是我得到的输出为FF
。这不是我的mac地址。 xx:xx:xx:xx:xx:ff
是我的mac地址。
public String getMacAddress() {
Enumeration<NetworkInterface> networks = null;
String macaddress=null;
try {
networks = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
NetworkInterface inter;
while (networks.hasMoreElements()) {
inter = networks.nextElement();
byte[] mac = null;
try {
mac = inter.getHardwareAddress();
} catch (SocketException e) {
e.printStackTrace();
}
if (mac != null) {
for (int i = 0; i < mac.length; i++) {
macaddress=String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
System.out.println("");
}
}
return macaddress;
}
如何获取我的MAC地址?
答案 0 :(得分:0)
我发现了:
package com.mkyong;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class App{
public static void main(String[] args){
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
System.out.print("Current MAC address : ");
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();
}
}
}
输出:
当前IP地址:192.168.1.22 当前的MAC地址:00-26-B9-9B-61-BF
答案 1 :(得分:0)
我看到两个问题。
首先,您要重新分配macaddress
的值。意味着总是只有mac
的最后一个字节。第二个问题是您要遍历计算机具有的所有接口,因此即使您更改了
macaddress = String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
macaddress += String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
要附加而不是分配,您将获得一个包含计算机具有的所有MAC地址的字符串。另外,您还必须将macaddress
初始化为空字符串(因为您不能追加到null
)。
由于要遍历所有接口,如何返回Collection
而不是单个String
?另外使用StringBuilder
可能更合适。
public List<String> getMacAddress() { // Change return type from String to List<String>
Enumeration<NetworkInterface> networks = null;
try {
networks = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
NetworkInterface inter;
List<String> addresses = new ArrayList<>(); // Create list to store all MAC addresses
while (networks.hasMoreElements()) {
inter = networks.nextElement();
byte[] mac = null;
try {
mac = inter.getHardwareAddress();
} catch (SocketException e) {
e.printStackTrace();
}
if (mac != null) {
StringBuilder sb = new StringBuilder(); // Rather than appending with += use a String builder
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); // Use append on the string builder
}
addresses.add(sb.toString()); // Add MAC address to the Collection
}
}
return addresses; // Return collection rather than one String
}