最近在做一个小程序,需要用到在linux系统里编写C程序从而获取MAC地址,从网上搜了一遍,想总结一下。如果你就只需要单个功能的程序,可以采用方法一,见代码1,一般最好能够封装起来,写成获取MAC地址的函数再调用,可以采用方法二,见代码2。
代码1:
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <string.h> int main(int argc, char *argv[])
{ struct ifreq ifreq;
int sock; if(argc!=)
{
printf("Usage : ethname\n");
return ;
}
if((sock=socket(AF_INET,SOCK_STREAM,))<)
{
perror("socket");
return ;
}
strcpy(ifreq.ifr_name,argv[]);
if(ioctl(sock,SIOCGIFHWADDR,&ifreq)<)
{
perror("ioctl");
return ;
}
printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
(unsigned char)ifreq.ifr_hwaddr.sa_data[],
(unsigned char)ifreq.ifr_hwaddr.sa_data[],
(unsigned char)ifreq.ifr_hwaddr.sa_data[],
(unsigned char)ifreq.ifr_hwaddr.sa_data[],
(unsigned char)ifreq.ifr_hwaddr.sa_data[],
(unsigned char)ifreq.ifr_hwaddr.sa_data[]);
return ;
}
将代码写入一个C文件,名称随便取,姑且存为MAC_addr.c。
在linux下运行:gcc -o MAC_addr MAC_addr.c
下一条指令要十分注意,这个函数是带参数才能执行的,可以用以下指令:
./MAC_addr etho 即可获得MAC地址。
想用封装的形式,写成一个求MAC地址的函数,然后再调用此函数,可以用方法二,见代码2。
代码2:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h> //for struct ifreq int get_mac(char * mac, int len_limit) //返回值是实际写入char * mac的字符个数(不包括'\0')
{
struct ifreq ifreq;
int sock; if ((sock = socket (AF_INET, SOCK_STREAM, )) < )
{
perror ("socket");
return -;
}
strcpy (ifreq.ifr_name, "eth0"); //Currently, only get eth0 if (ioctl (sock, SIOCGIFHWADDR, &ifreq) < )
{
perror ("ioctl");
return -;
} return snprintf (mac, len_limit, "%X:%X:%X:%X:%X:%X", (unsigned char) ifreq.ifr_hwaddr.sa_data[], (unsigned char) ifreq.ifr_hwaddr.sa_data[], (unsigned char) ifreq.ifr_hwaddr.sa_data[], (unsigned char) ifreq.ifr_hwaddr.sa_data[], (unsigned char) ifreq.ifr_hwaddr.sa_data[], (unsigned char) ifreq.ifr_hwaddr.sa_data[]);
} int main()
{
char szMac[];
int nRtn = get_mac(szMac, sizeof(szMac));
if(nRtn > )
{
fprintf(stderr, "MAC ADDR: %s\n", szMac);
}
return ;
}
将代码写入一个C文件,姑且存为MAC_addr.c。
在linux下运行:gcc -o MAC_addr MAC_addr.c
./MAC_addr 即可获得MAC地址。
亲测以上方法都是通过的,欢迎讨论是否还有更好的方法!