在开发中需要获取电脑的mac地址,记录一下java快速获取mac地址的方法,也可获取到ip地址。
public static void main(String[] args) throws UnknownHostException, SocketException {
//得到IP,输出主机/ip地址
InetAddress ia = InetAddress.getLocalHost();
System.out.println(ia);
//根据主机和ip获取mac地址
getLocalMac(ia);
}
public static void getLocalMac(InetAddress ia) throws SocketException {
//获取网卡,获取地址
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
System.out.println("mac数组长度:"+mac.length);
StringBuffer sb = new StringBuffer("");
for(int i=0; i<mac.length; i++) {
if(i!=0) {
//每2位用“-”拼接
sb.append("-");
}
//字节转换为整数
int temp = mac[i] & 0xff;
String str = Integer.toHexString(temp);
System.out.println("每8位:"+str);
if(str.length()==1) {
//十位补0
sb.append("0"+str);
}else {
sb.append(str);
}
}
System.out.println("本机MAC地址:"+sb.toString().toUpperCase());
}