如何通过C的方式在android NDK下面查找本机的mac地址

本文介绍了一种通过C语言在Android Native Development Kit (NDK)环境下获取设备MAC地址的方法,提供了直接的代码示例。

废话少说直接上代码

bool GetMac(char *pBuffer)
{
	struct ifreq *ifr;
    struct ifconf ifc;
    int s, i;
    int numif;

    // find number of interfaces.
    memset(&ifc, 0, sizeof(ifc));
    ifc.ifc_ifcu.ifcu_req = NULL;
    ifc.ifc_len = 0;

    if ((s = ::socket(PF_INET, SOCK_STREAM, 0)) < 0) 
	{
		CCLog("SgProfile::GetMac 111111");
        return false;
    }

    if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
	{
		CCLog("SgProfile::GetMac 222222");
		return false;
    }

    if ((ifr = (ifreq*) malloc(ifc.ifc_len)) == NULL)
	{
		CCLog("SgProfile::GetMac 333333");
        return false;
    }

    ifc.ifc_ifcu.ifcu_req = ifr;

    if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
	{
		CCLog("SgProfile::GetMac 333333 ioctl SIOCGIFCONF error!");
        return false;
    }

    numif = ifc.ifc_len / sizeof(struct ifreq);

    for (i = 0; i < numif; i++)
	{
		struct ifreq *r = &ifr[i];
		struct sockaddr_in *sin = (struct sockaddr_in*)&r->ifr_addr;
		if (!strcmp(r->ifr_name, "lo"))
			continue; // skip loopback interface

		// get MAC address
		if(ioctl(s, SIOCGIFHWADDR, r) < 0)
		{
			CCLog("SgProfile::GetMac 333333 ioctl(SIOCGIFHWADDR) error!");
			continue;
		}
		
		memcpy(pBuffer,r->ifr_hwaddr.sa_data,6); 
		close(s);
		free(ifr);
					
		return true;
	 }
	 
	 return false;
}

在国外论坛里面找的,写在这里以备忘!     


评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值