欢迎光临
我们一直在努力

Linux c 获取本地MAC地址方法

获取方法如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include  
#include  
#include   
#include   
#include    
#include   
#include  

void  get_mac_name(char *name, char *dev_name)
{
	struct ifreq ifreq;
	int sock;
	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("socket");
		goto __finish;
	}
	strcpy(ifreq.ifr_name, dev_name);
	if (ioctl(sock, SIOCGIFHWADDR, &ifreq) < 0)
	{
		perror("ioctl");
		goto __finish;
	}
	printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
		(unsigned char)ifreq.ifr_hwaddr.sa_data[0],
		(unsigned char)ifreq.ifr_hwaddr.sa_data[1],
		(unsigned char)ifreq.ifr_hwaddr.sa_data[2],
		(unsigned char)ifreq.ifr_hwaddr.sa_data[3],
		(unsigned char)ifreq.ifr_hwaddr.sa_data[4],
		(unsigned char)ifreq.ifr_hwaddr.sa_data[5]);
	char mac1[32], mac4[32], mac5[32], mac6[32];
	sprintf(mac1, "%02x", (unsigned char)ifreq.ifr_hwaddr.sa_data[0]);
	sprintf(mac4, "%02x", (unsigned char)ifreq.ifr_hwaddr.sa_data[3]);
	sprintf(mac5, "%02x", (unsigned char)ifreq.ifr_hwaddr.sa_data[4]);
	sprintf(mac6, "%02x", (unsigned char)ifreq.ifr_hwaddr.sa_data[5]);
	sprintf(name, "%s%s%s%c", mac4, mac5, mac6, mac1[0]);

__finish:
	if (strlen(name) != 7)
	{
		sprintf(name, "%s", "0000001");
		printf("mac name len is error,len = %d, mac name is %s default mac_name:%s\n", (int)strlen(name), name, "0000001");
	}
}
赞(1) 打赏
未经允许不得转载:huangea的博客 » Linux c 获取本地MAC地址方法
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

有趣的网站

联系我们联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏