码迷,mamicode.com
首页 > 系统相关 > 详细

[转]OpenWRT之获取MAC地址

时间:2015-11-08 15:03:09      阅读:641      评论:0      收藏:0      [点我收藏+]

标签:

#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

[转]OpenWRT之获取MAC地址

标签:

原文地址:http://www.cnblogs.com/qvbrgw/p/4947109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!