获取十六进制的MAC地址并且转换为byte数组

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011976443/article/details/79893542
1.把十六进制的Mac地址转换为byte数组输出
(1)mac.java 中添加方法


public void setMac(){
String source = Util.getMac();
byte[]SrcMac = new byte[6];
String[] strs = source.replaceAll(" ","").spilit(":");
for(int i = 0;i < source.length;i++){
SrcMac[i] = Util.hexString2byte[strs[i]];
}

}
(2)Util中添加方法
public static bytehexString2byte(String str){
str = str.toUpperCase();//将字符串中的小写转化为大写
char[] chars = str.toCharArray();
byte b = (byte)((char2byte)(chars[0]<<4)|char2byte(char[1]));
return b;
}
public static byte char2byte(char c){
return (byte)"0123456789ABCDEF".indexOf(c);//返回c中包含byte中数据的索引
}


2.把byte型数组转化为int方法


public static int writebyteArr2int(byte[] bytes,int idx,int len){
int data =0;
if(len == 1){
data = (int)(bytes[idx+0])&0x000000ff;
}else if(len == 2){
data = (int)(bytes[idx+0]<<8)&0x0000ff00|(int)(bytes[idx+1])&0x000000ff;

}else if(len == 3){
data = (int)(bytes[idx+0]<<16)&0x00ff0000|(int)(bytes[idx+1])&0x0000ff00|(int)(bytes[idx+2])&0x000000ff;

}else if(len == 3){
data = (int)(bytes[idx+0]<<24)&0xff000000|(int)(bytes[idx+1])&0x00ff0000|(int)(bytes[idx+2])&0x0000ff00|(int)(bytes[idx+3])&0x000000ff;

}
return data;
}
3.将int型转化为byte型数组
public static void writeintArr2byte(int data,byte[]bytes,int idx,int len){
for(int i = 0;i < len;i++){
bytes[idx+i] = (byte)(data>>(8*(len - i -1)&0xff));
}

}

4.获取终端mac地址


public static String getMac(){
String result;
String Mac;
result = callCmd("busybox ifconfig","HWaddr");
if(result == null){
return "网络出错";
}

if(result.length()>0 &&result.contains("HWaddr")==true){
Mac = result.substring(result.indexOf("HWaddr")+6,result.length -1);//产生一个子串,子串中只有mac的内容
result = mac;

}
return result;
}


public static  String callCmd(String cmd,String filter){

String result;
String line;
try{
Process proc = Runtime.getRuntime().exec(cmd);
InputStreamReader is = new InputStreamReader(proc.getInputstream);
BufferedReader br = new BufferedReader(is);//存放输入流内容
//只取包含filter的行
while((line = br.readLine()) != null&&line.contains(filter) == false){

}
result = line;
}catch(Exception e){
e.printStackTrace();
}
return result;
}

猜你喜欢

转载自blog.csdn.net/u011976443/article/details/79893542