[转]OpenWRT之获取MAC地址
#include <stdlib.h>
#include <stdio.h>
#include <net/if_arp.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
struct sockaddr_in sin = { 0 };
struct arpreq myarp = { { 0 } };
int sockfd;
unsigned char *ptr;
if(argc!=2) {
printf("usage: %s <IP address>\n",argv[0]);
exit(0);
}
sin.sin_family = AF_INET;
if(inet_aton(argv[1], &sin.sin_addr)==0) {
printf("%s: IP address '%s' not valid\n",argv[0],argv[1]);
exit(0);
}
memcpy(&myarp.arp_pa, &sin, sizeof(myarp.arp_pa));
strcpy(myarp.arp_dev, "eth0");
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
printf("%s: cannot open socket\n",argv[0]);
exit(0);
}
if (ioctl(sockfd, SIOCGARP, &myarp) == -1) {
printf("%s: no entry in arp_cache for '%s'\n",argv[0],argv[1]);
exit(0);
}
ptr = &myarp.arp_ha.sa_data[0];
printf("%s: MAC address for '%s' is : ",argv[0],argv[1]);
printf("%x:%x:%x:%x:%x:%x\n",*ptr, *(ptr+1),*(ptr+2),*(ptr+3),*(ptr+4),*(ptr+5));
return 1;
}
[root@mini /test]$./getMAC 192.168.1.100
./getMAC: no entry in arp_cache for '192.168.1.100'
[root@mini /test]$./getMAC 192.168.1.1
./getMAC: MAC address for '192.168.1.1' is : 6c:e8:73:e4:3c:80
原文地址:http://blog.csdn.net/suiyuan19840208/article/details/8483026