WifiManager wm = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE);
String macAddress = wm.getConnectionInfo().getMacAddress();
它是十六进制格式的字符串,例如:
"00:23:76:B7:2B:4D"
我想将此字符串转换为字节数组,以便我可以在其上使用MessageDigest
sha1
我使用\x
模块使用excaping :
代替hashlib
,在Python中使用它。
但我会在android / java中这样做吗? 谢谢!
答案 0 :(得分:3)
此代码:
Byte.parseByte(mac[i], 16);
没有正确解析以字母开头的十六进制数字:“AE”,“EF”等...
修改后的代码:
WifiManager wm = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
if (wm != null) {
String[] mac = wm.getConnectionInfo().getMacAddress().split(":");
byte[] macAddress = new byte[6]; // mac.length == 6 bytes
for(int i = 0; i < mac.length; i++) {
macAddress[i] = Integer.decode("0x" + mac[i]).byteValue();
}
}
答案 1 :(得分:0)
WifiManager wm = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE);
byte[] macAddress = wm.getConnectionInfo().getMacAddress().getBytes();
修订解决方案:
WifiManager wm = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE);
String[] mac = wm.getConnectionInfo().getMacAddress().split(":");
byte[] macAddress = new byte[6];
for(int i = 0; i < mac.length; i++) {
macAddress[i] = Byte.parseByte(mac[i], 16);
}
答案 2 :(得分:0)
通过这个你在字节数组中得到mac地址,所以你不需要转换它。
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class App{
public static void main(String[] args){
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
System.out.print("Current MAC address : ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println(sb.toString());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e){
e.printStackTrace();
}
}
}
/ 从此处复制:从http://www.mkyong.com/java/how-to-get-mac-address-in-java/comment-page-1/#comment-139182 /
复制