利用C语言获取设备的MAC address
利用C语言获取设备的MAC address
MAC address --> Medium Access Control layer address
//
// http://www.binarytides.com/c-program-to-get-mac-address-from-interface-name-on-linux/
#include <stdio.h> //printf
#include <string.h> //strncpy
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h> //ifreq
#include <unistd.h> //close
void getmacaddr(char *macaddr, const char *interface)
{
int fd;
struct ifreq ifr;
const char *iface = interface;
unsigned char *mac;
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
ioctl(fd, SIOCGIFHWADDR, &ifr);
close(fd);
mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
sprintf(macaddr, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}
int main()
{
char macaddress[17]={'0'};
getmacaddr(macaddress, "eth0");
int i=0;
for(i=0;i<sizeof(macaddress);i++)
{
printf("%c", macaddress[i]);
}
printf("\n");
return 0;
}
这里有一个需要玩味的是,函数getmacaddr()
同样可以使用二维字符之称char **
作为参数,但是需要注意的是,不能直接拿参数来操作,需要设置临时变量。
void _getmacaddr(char **macaddr, const char *interface)
{
int fd;
struct ifreq ifr;
const char *iface = interface;
unsigned char *mac;
char **newaddress = macaddr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
ioctl(fd, SIOCGIFHWADDR, &ifr);
close(fd);
mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
sprintf( *newaddress, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}