Chinaunix首页 | 论坛 | 博客
  • 博客访问: 280117
  • 博文数量: 84
  • 博客积分: 3186
  • 博客等级: 中校
  • 技术积分: 852
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-15 15:46
文章分类

全部博文(84)

文章存档

2015年(1)

2014年(12)

2011年(29)

2010年(42)

分类: LINUX

2011-02-20 19:40:24

转帖自:
 
 
通过已经连接的socket文件获取:
  1. int getpeermac( int sockfd, char *buf )
  2. {
  3.     int ret =0;
  4.     struct arpreq arpreq;
  5.     struct sockaddr_in dstadd_in;
  6.     socklen_t len = sizeof( struct sockaddr_in );
  7.     memset( &arpreq, 0, sizeof( struct arpreq ));
  8.     memset( &dstadd_in, 0, sizeof( struct sockaddr_in ));
  9.     if( getpeername( sockfd, (struct sockaddr*)&dstadd_in, &len ) < 0 )
  10.         err_err("getpeername()");
  11.     else
  12.     {
  13.         memcpy( &arpreq.arp_pa, &dstadd_in, sizeof( struct sockaddr_in ));
  14.         strcpy(arpreq.arp_dev, "eth1");
  15.         arpreq.arp_pa.sa_family = AF_INET;
  16.         arpreq.arp_ha.sa_family = AF_UNSPEC;
  17.         if( ioctl( sockfd, SIOCGARP, &arpreq ) < 0 )
  18.             err_err("ioctl SIOCGARP");
  19.         else
  20.         {
  21.             unsigned char* ptr = (unsigned char *)arpreq.arp_ha.sa_data;
  22.             ret = sprintf(buf, "%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5));
  23.         }
  24.     }
  25.     return ret;
  26. }
通过IP获取:
  1. int getpeermac_by_ip(char *ipaddr, char* buf)
  2. {
  3.     int sockfd;
  4.     unsigned char *ptr;
  5.     struct arpreq arpreq;
  6.     struct sockaddr_in *sin;
  7.     struct sockaddr_storage ss;
  8.     char addr[INET_ADDRSTRLEN+1];
  9.   
  10.     memset(addr, 0, INET_ADDRSTRLEN+1);
  11.     memset(&ss, 0, sizeof(ss));
  12.     if (argc != 2) {
  13.         printf("USAGE arpg ip_addr\n");
  14.         return -1;
  15.     }
  16.     sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  17.     if (sockfd == -1) {
  18.         perror("socket error");
  19.         return -1;
  20.     }
  21.     sin = (struct sockaddr_in *) &ss;
  22.     sin->sin_family = AF_INET;
  23.     if (inet_pton(AF_INET, argv[1], &(sin->sin_addr)) <= 0) {
  24.         perror("inet_pton error");
  25.         return -1;
  26.     }
  27.     sin = (struct sockaddr_in *) &arpreq.arp_pa;
  28.     memcpy(sin, &ss, sizeof(struct sockaddr_in));
  29.     strcpy(arpreq.arp_dev, "eth1");
  30.     arpreq.arp_ha.sa_family = AF_UNSPEC;
  31.     if (ioctl(sockfd, SIOCGARP, &arpreq) < 0) {
  32.         perror("ioctl SIOCGARP: ");
  33.         return -1;
  34.     }
  35.     ptr = (unsigned char *)arpreq.arp_ha.sa_data;
  36.     sprintf(buf,"%x:%x:%x:%x:%x:%x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5));
  37.     return 0;
  38. }
阅读(1673) | 评论(0) | 转发(1) |
0

上一篇:烦恼多多

下一篇:三星面经

给主人留下些什么吧!~~