Java-获取Linux系统的MAC地址
我正在尝试使用以下代码获取 Linux 系统的 MAC 地址:
try {
ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
// System.out.print("Current MAC address: ");
for (int i = 0; i < mac.length; i++) {
is = is + Integer.parseInt(
String.format("%02X%s", mac[i], (i < mac.length - 1) ? "" : ""),16);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
但它只是崩溃了...有人知道为什么吗?
I'm trying to get the MAC address of a linux system with this code:
try {
ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
// System.out.print("Current MAC address: ");
for (int i = 0; i < mac.length; i++) {
is = is + Integer.parseInt(
String.format("%02X%s", mac[i], (i < mac.length - 1) ? "" : ""),16);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
But it just crashes... does anyone know why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能有多个网络接口,我不会指望接口的名称。我建议您检查所有接口并查找具有 MAC 地址的接口。
您可以使用此示例作为基准:
You might have more than one network interface and I would not count on the interface's name. I suggest you to go over all the interfaces and look for one that has a MAC address.
You can use this example as a base line:
从您的评论中,显然
network
为null
,这意味着getByInetAddress()
无法找到具有该 IP 地址的接口(请参阅 JavaDocs: http://download.oracle.com/javase/1.5.0/docs/api/java/net/NetworkInterface.html#getByInetAddress(java.net.InetAddress))。From your comments, clearly
network
isnull
, which means thatgetByInetAddress()
could not find an interface with that IP address (see the JavaDocs: http://download.oracle.com/javase/1.5.0/docs/api/java/net/NetworkInterface.html#getByInetAddress(java.net.InetAddress)).只需对 Guy 的代码进行一个小修改:
此代码已在 Windows、Linux (Ubuntu) 和 Mac OS X 上成功测试。
因为网络可以为空,所以我忽略所有空情况,也忽略空地址。我认为如果我们不这样做,我们就会看到崩溃。我选择第一个找到的地址,它可以工作,但可能是错误的,所以只需测试一下即可。
Just a small modification of the code of Guy :
This code has been tested on Windows, Linux (Ubuntu) and Mac OS X with success.
Because the network can be null, I ignore all null cases and I also ignore empty addresses. I think that if we don't do this, we view the crash. I choose the first found address and it works but it may be wrong, so just test it.