Monday, November 2, 2009

如何從Linux系統抓MAC Address

在Linux 平台上面,可以使用ioctl的方式來得知網路的的MAC Address.

-----------------------
#include 

#include /* for strncpy */

#include
#include
#include
#include
#include

int
main()
{
int fd;
struct ifreq ifr;

fd = socket(AF_INET, SOCK_DGRAM, 0);

ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);

ioctl(fd, SIOCGIFHWADDR, &ifr);

close(fd);

/* display result */
printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
(unsigned char)ifr.ifr_hwaddr.sa_data[0],
(unsigned char)ifr.ifr_hwaddr.sa_data[1],
(unsigned char)ifr.ifr_hwaddr.sa_data[2],
(unsigned char)ifr.ifr_hwaddr.sa_data[3],
(unsigned char)ifr.ifr_hwaddr.sa_data[4],
(unsigned char)ifr.ifr_hwaddr.sa_data[5]);

return 0;
}


Ref http://www.geekpage.jp/en/programming/linux-network/get-macaddr.php

No comments: