代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <linux/if.h>
#include <sys/ioctl.h>
int getnicmac(char *dest, int size, char *dev)
{
int fd = 0;
int found = 0;
struct ifreq req;
strcpy(dest, "");
/* Create socket to do ioctl. */
if ((fd = socket(PF_INET, SOCK_DGRAM, 0))) {
/* Set ifrn_name to device name eg. "eth0" */
snprintf(req.ifr_ifrn.ifrn_name, IFNAMSIZ, dev);
/* Do ioctl to get hardware address (MAC) */
if (!(ioctl(fd, SIOCGIFHWADDR, &req))) {
/* Format MAC into colon seperated string format. */
snprintf(dest, size, "%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X",
req.ifr_ifru.ifru_hwaddr.sa_data[0] & 0xff,
req.ifr_ifru.ifru_hwaddr.sa_data[1] & 0xff,
req.ifr_ifru.ifru_hwaddr.sa_data[2] & 0xff,
req.ifr_ifru.ifru_hwaddr.sa_data[3] & 0xff,
req.ifr_ifru.ifru_hwaddr.sa_data[4] & 0xff,
req.ifr_ifru.ifru_hwaddr.sa_data[5] & 0xff);
found = 1;
}
}
if (fd)
close(fd);
return (found);
}
int main(int argc, char **argv)
{
char mac[32] = "";
int ret = 0;
ret = getnicmac(mac, 512, "eth0");
printf("ret:%d\n", ret);
printf("Mac:%s\n", mac);
return 0;
}
运行结果:
ret:1
Mac:00:18:8B:2F:1D:A4
--
/**************************************/
Name: Xiong Feng
E-mail:linux0818@gmail.com
MSN:linux0818@hotmail.com
QQ:23562033
Address: GuangZhou.China
/**************************************/
没有评论:
发表评论