如何在Android本机代码中获取mac地址

时间:2016-04-11 08:38:55

标签: android android-ndk

我可以使用此C代码获取mac地址:

struct ifreq s;
char buffer[12 + 1];
int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
int i, j;
memset(buffer, 0 , sizeof(buffer));
strcpy(s.ifr_name, "wlan0");

if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
    memcpy(mac, s.ifr_addr.sa_data, 6);
    return 1;
}

我想在Android中获取mac地址。但是这段代码没有给出MAC地址。 if (0 == ioctl(fd, SIOCGIFHWADDR, &s)始终是假的。

我在https://groups.google.com/d/msg/android-ndk/6Y-0Eid3mGw/6bFvtap8xJIJ

中找到了一个代码

但是这段代码给出了错误:

ioctl(SIOCGIFHWADDR) error 

它会提供错误的mac地址,例如00:00:00:7C::00:01

如何在Android原生代码中获取mac地址?

2 个答案:

答案 0 :(得分:0)

您必须连接到WiFi网络,然后尝试获取mac地址。

答案 1 :(得分:0)

此代码适用于Nexus 5:

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <linux/sockios.h>
#include <linux/if.h>
#include <linux/in.h>


int get_mac_addr(char *mac_addr)
{
  int sockfd;
  struct ifreq ifr;

  if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) >= 0) {
    //strncpy(ifr.ifr_name, "eth0", IFNAMESIZE);
    strncpy(ifr.ifr_name, "wlan0", IFNAMSIZ);

    ifr.ifr_addr.sa_family = AF_INET;

    if (ioctl(sockfd, SIOCGIFHWADDR, (char*) &ifr) == 0) {
      sprintf(mac_addr, "%02X:%02X:%02X:%02X:%02X:%02X", 
              (unsigned char) ifr.ifr_ifru.ifru_hwaddr.sa_data[0], (unsigned char) ifr.ifr_ifru.ifru_hwaddr.sa_data[1],
              (unsigned char) ifr.ifr_ifru.ifru_hwaddr.sa_data[2], (unsigned char) ifr.ifr_ifru.ifru_hwaddr.sa_data[3],
              (unsigned char) ifr.ifr_ifru.ifru_hwaddr.sa_data[4], (unsigned char) ifr.ifr_ifru.ifru_hwaddr.sa_data[5]);
      return 0;  
    }
  }
  /* error */
  return -1;
}



int main(int argc, char *argv[], char *envp[])
{
  char mac_addr[80] = {0};
  printf( "MAC = %d, %s\n", get_mac_addr(mac_addr), mac_addr );

  return 0;
}