最近在做一个小程序,需要用到在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!=2)
{
printf("Usage : ethname\n");
return 1;
}
if((sock=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
return 2;
}
strcpy(ifreq.ifr_name,argv[1]);
if(ioctl(sock,SIOCGIFHWADDR,&ifreq)<0)
{
perror("ioctl");
return 3;
}
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]);
return 0;
}
将代码写入一个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, 0)) < 0)
{
perror ("socket");
return -1;
}
strcpy (ifreq.ifr_name, "eth0"); //Currently, only get eth0
if (ioctl (sock, SIOCGIFHWADDR, &ifreq) < 0)
{
perror ("ioctl");
return -1;
}
return snprintf (mac, len_limit, "%X:%X:%X:%X:%X:%X", (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]);
}
int main()
{
char szMac[18];
int nRtn = get_mac(szMac, sizeof(szMac));
if(nRtn > 0)
{
fprintf(stderr, "MAC ADDR: %s\n", szMac);
}
return 0;
}
将代码写入一个C文件,姑且存为MAC_addr.c。
在linux下运行:gcc -o MAC_addr MAC_addr.c
./MAC_addr 即可获得MAC地址。
亲测以上方法都是通过的,欢迎讨论是否还有更好的方法!