公 告

欢迎各位网友添加友情链接,在您添加本博客:http://linux0818.blogspot.com/ 做为链接后, E-mail:linux0818@gmail.com给我,我将将您的网址添加到本博客。

2009年3月23日星期一

OpenSource之获取Linux Mac地址

代码如下:

#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
/**************************************/

没有评论:

发表评论