JAVA获取指定的类型的本机MAC地址

前面我们运维小伙在部署的时候,发现在真实服务器获取不到mac地址或者获取不到指定类型的mac地址,写程序记录如下

import com.google.common.base.Strings;

import java.net.NetworkInterface;
import java.util.Enumeration; public class MacHelper { private static MacHelper instance; public static MacHelper getInstance() { if (instance == null) {
synchronized (MacHelper.class) {
instance = new MacHelper();
}
} return instance;
} /**
* 获取本地IP
*
* @return String
*/
public String getFirstLocalMac() {
String startName = "eth", symbol = "";
return getFirstLocalMac(startName, symbol);
} /**
* 获取本地IP
*
* @return String
*/
public String getFirstLocalMac(String startName, String symbol) { try { Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); while (enumeration.hasMoreElements()) { NetworkInterface networkInterface = enumeration.nextElement(); if (networkInterface == null) {
continue;
} if (!(networkInterface.getName().equals(startName) ||
networkInterface.getName().startsWith(startName))) {
continue;
} //获取网卡,获取地址
byte[] mac = networkInterface.getHardwareAddress(); if (mac == null || mac.length <= 0) {
continue;
} StringBuilder sb = new StringBuilder(); int i = 0; for (byte b : mac) {
//字节转换为整数
int temp = b & 0xff;
String str = Integer.toHexString(temp); if (!Strings.isNullOrEmpty(symbol) && i == 0) {
sb.append(symbol);
} if (str.length() == 1) {
sb.append("0").append(str);
} else {
sb.append(str);
} i++;
} return sb.toString().toLowerCase(); } } catch (Exception e) {
e.printStackTrace();
} return "";
}
}

  

上一篇:ajax及其工作原理


下一篇:java获取变量的类型