java 如何获取机器的mac地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11884696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get machines mac address
提问by Sagar Badave
I want get machines' MAC address..but below written code only display the MAC address when Internet is connected to my machine other it will return null... I am using windows 7
我想要获取机器的 MAC 地址..但是下面的编写代码仅在 Internet 连接到我的机器时显示 MAC 地址,否则它将返回空...我使用的是 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();
}
}
}
回答by gYanI
Try this it should work in both Linux and windows
试试这个它应该可以在 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();
}
}
回答by gYanI
Seems like you are trying to get the MAC address by IP address. An IP address exists onlywhen you are connected successfullyto the Internet. Otherwise, it will be null
, as you state.
似乎您正在尝试通过 IP 地址获取 MAC 地址。仅当您成功连接到 Internet时,IP 地址才存在。否则,null
正如你所说的那样。
Try this: NetworkInterface.getHardwareAddress()
.
试试这个:NetworkInterface.getHardwareAddress()
。
If you want the MAC address of all network interfaces on your computer, try this: NetworkInterface.getNetworkInterfaces()
.
如果您想要计算机上所有网络接口的 MAC 地址,请尝试以下操作:NetworkInterface.getNetworkInterfaces()
。
EDIT: After reviewing the code again, I realize that you have my suggestion implemented. However, you are only trying to obtain the MAC address ifyou have a valid IP. You will not have a valid IP if are not connected to the Internet.
编辑:再次查看代码后,我意识到您已实施我的建议。但是,如果您有一个有效的 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());
}
回答by Petr Pudlák
The problem is probably caused by the fact that when your machine isn't connected to the Internet, your network card doesn't have an assigned IP address. And you are trying to look up the network interface by an IP address.
问题可能是由于当您的机器未连接到 Internet 时,您的网卡没有分配的 IP 地址。并且您正在尝试通过 IP 地址查找网络接口。
I suggest you to enumerate all network interfaces instead, and pick the one you need:
我建议您改为枚举所有网络接口,然后选择您需要的接口:
import java.net.*;
import java.util.*;
public class App {
protected static String formatMac(byte[] mac) {
if (mac == null)
return "UNKNOWN";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
for(Enumeration<NetworkInterface> e
= NetworkInterface.getNetworkInterfaces();
e.hasMoreElements(); )
{
NetworkInterface ni = e.nextElement();
System.out.println(ni.getName() + " - " + formatMac(ni.getHardwareAddress()));
}
}
}
This should solve the problem and work without any Internet connection.
这应该可以解决问题并且无需任何 Internet 连接即可工作。