java 获取当前mac地址_Java:获取本机的所有Mac地址

public class Mac {

public static void main(String[] args) {

try {

Enumeration enumeration = NetworkInterface.getNetworkInterfaces();

while (enumeration.hasMoreElements()) {

StringBuffer stringBuffer = new StringBuffer();

NetworkInterface networkInterface = enumeration.nextElement();

if (networkInterface != null) {

byte[] bytes = networkInterface.getHardwareAddress();

if (bytes != null) {

for (int i = 0; i < bytes.length; i++) {

if (i != 0) {

stringBuffer.append("-");

}

int tmp = bytes[i] & 0xff; // 字节转换为整数

String str = Integer.toHexString(tmp);

if (str.length() == 1) {

stringBuffer.append("0" + str);

} else {

stringBuffer.append(str);

}

}

String mac = stringBuffer.toString().toUpperCase();

System.out.println(mac);

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

在我的开发机(Windows)上运行上面代码可以获取多个Mac地址(安装了VM有若干虚拟的),但在服务器上却只能获取到一个Mac地址,请问这是为什么呢?

ec202393537edf6a07502e8d5ea24155.png

d023fb1cf787366fd6bf2cd2d4ce67aa.png

我却只能获取到【XX-XX-54-B3-6B-28】这一个Mac请问为什么呢?应该一个是有线网卡,一个是无线网卡获取到两个才对,可是【XX-XX-54-B3-6B-29】却获取不到

===========================分割线============================

仍未找到问题所在,临时解决办法是Windows中使用以上代码获取所有Mac,而在Linux(CentOS 7.0)中通过读取

public class Mac {

public static void main(String[] args) throws Exception {

StringBuffer sb = new StringBuffer();

try {

String str = "cat /sys/class/net/*/address | sed -n '1p'";

String[] cmd = new String[] { "/bin/sh", "-c", str };

Process process = Runtime.getRuntime().exec(cmd);

BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));

String line;

while ((line = br.readLine()) != null) {

sb.append(line);

}

} catch (IOException e) {

e.printStackTrace();

}

String mac = sb.toString().replace(":", "-").toUpperCase();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值