java – 如何获取机器的mac地址
发布时间:2020-12-15 05:09:10 所属栏目:Java 来源:网络整理
导读:我想得到机器的MAC地址..但是下面写的代码只显示互联网连接到我的机器的MAC地址,否则它将返回null …我正在使用 Windows 7 import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.net.UnknownHostExce
|
我想得到机器的MAC地址..但是下面写的代码只显示互联网连接到我的机器的MAC地址,否则它将返回null …我正在使用
Windows 7
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
class test
{
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();
}
}
}
解决方法
试试这个应该适用于Linux和Windows
public static void main(String[] args) {
String command = "/sbin/ifconfig";
String sOsName = System.getProperty("os.name");
if (sOsName.startsWith("Windows")) {
command = "ipconfig";
} else {
if ((sOsName.startsWith("Linux")) || (sOsName.startsWith("Mac"))
|| (sOsName.startsWith("HP-UX"))) {
command = "/sbin/ifconfig";
} else {
System.out.println("The current operating system '" + sOsName
+ "' is not supported.");
}
}
Pattern p = Pattern
.compile("([a-fA-F0-9]{1,2}(-|:)){5}[a-fA-F0-9]{1,2}");
try {
Process pa = Runtime.getRuntime().exec(command);
pa.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
pa.getInputStream()));
String line;
Matcher m;
while ((line = reader.readLine()) != null) {
m = p.matcher(line);
if (!m.find())
continue;
line = m.group();
break;
}
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
