2012-04-14 12 views
0
WifiManager wm = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE); 
String macAddress = wm.getConnectionInfo().getMacAddress(); 

它是十六进制格式的字符串,例如:转换机器人MAC地址十六进制串成字节[]中的java

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

欲将此字符串转换成一个字节数组,使得我可以使用它

MessageDigest SHA1我得到了它在Python的工作,通过使用excaping \x而不是:使用hashlib模块。

但我会在android/java中执行它吗? 谢谢!

回答

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); 
} 
+0

在这方面,'getBytes'将返回34个的Unicode码点,而不是6个字节的MAC地址。 – Gabe 2012-04-14 01:40:09

2

此代码:

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(); 
    } 
} 
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/

相关问题