我想得到机器的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
试试这个应该适用于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();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
好像你正试图通过IP地址获取MAC地址.仅当您成功连接到Internet 时,才存在IP地址.否则,null就像你所说的那样.
试试这个:NetworkInterface.getHardwareAddress().
如果您想要计算机上所有网络接口的MAC地址,请尝试以下方法:NetworkInterface.getNetworkInterfaces().
编辑:再次审查代码后,我意识到你已经实施了我的建议.但是,如果您具有有效的IP ,则只尝试获取MAC地址.如果未连接到Internet,您将没有有效的IP.
public static void main(String[] args)
{
NetworkInterface network;
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());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13033 次 |
| 最近记录: |