欢迎光临
我们一直在努力

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地址方法

评论 抢沙发

有趣的网站

支持快讯、专题、百度收录推送、人机验证、多级分类筛选器,适用于垂直站点、科技博客、个人站,扁平化设计、简洁白色、超多功能配置、会员中心、直达链接、文章图片弹窗、自动缩略图等...

联系我们联系我们

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

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册