1
 WifiManager wm = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE);
 String macAddress = wm.getConnectionInfo().getMacAddress();

它是一个十六进制格式的字符串,例如:

"00:23:76:B7:2B:4D"

我想将此字符串转换为字节数组,以便可以MessageDigest在其上使用 sha1

我通过使用 excaping\x而不是:使用hashlib模块在 Python 中工作。

但我会在 android/java 中做吗?谢谢!

4

4 回答 4

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();
    }
}
于 2012-07-30T10:07:15.563 回答
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复制/

于 2013-10-28T10:31:59.350 回答
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);
}
于 2012-04-14T01:36:22.907 回答
0

在 android API 级别 28 中,有一种更简单的方法:https ://developer.android.com/reference/android/net/MacAddress 。

android.net.MacAddress.fromString(s).toByteArray();
于 2021-09-25T22:49:43.010 回答