Linux 下获取LAN中指定IP的网卡的MAC(物理地址)

2016-09 睿丰德RFID软件系统集成商
睿丰德科技 专注RFID识别技术和条码识别技术与管理软件的集成项目。质量追溯系统、MES系统、金蝶与条码系统对接、用友与条码系统对接

// all.h
// 2005/06/20,a.m. wenxy

#ifndef _ALL_H
#define _ALL_H

#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <string.h>
#include <errno.h> 

// ---------------------
// 创建ARP包的头文件
#include<netinet/in.h>
#include<arpa/inet.h>
/* #include<linux/if_ether.h> */    
#include<ctype.h>
#include <fcntl.h>
// ---------------------

#include <unistd.h>

#include <string>
#include <iostream>
using namespace std;


#define MAX_MAC_LEN 24  // MAC字串缓冲区的最大长度(byte)
#define COMPART_MAC ":"  // MAC字串的分格符, Warnning:修改此宏,必须再修改源程序!!!


#endif /* end _ALL_h */

// end file

// -------------------------------------------------------------------------------------------------------------

// main.cpp
// 2005/06/20,a.m. wenxy

#include "all.h"


// function declare
static string GetLocalMac(string & strEth); // get loacl NIC's MAC
void set_ip_addr(char *,char *);   // 填充IP
void set_hw_addr(char buf[], char *str); // 填充MAC
static string GetMacByIP(string strSrcIP, string strSrcMAC, string strDesIP ,string strNIC); // 获取指定IP的MAC


/*
#define SRC_IP   "10.0.1.77"   // 源IP
#define DES_IP   "10.0.1.35"   // 目的IP
#define LOCAL_HW        "00:C0:4C:39:0D:6F" // 10.0.1.77的eth0的MAC
#define DEVICE          "eth0"    // 接口
*/
#define PADD_MAC  "00:00:00:00:00:00" // 填充的MAC
#define DES_MAC   "FF:FF:FF:FF:FF:FF" // 广播MAC
#define ARP_SEND_COUNT 3     // 发送ARP请求的ARP包的个数


 struct ether_header
 {
  unsigned char  ether_dhost[6];          /* destination eth addr */
  unsigned char  ether_shost[6];          /* source ether addr    */
  unsigned short ether_type;              /* packet type ID field */
 };
 struct arp_header
 {
  unsigned short int ar_hrd;              /* Format of hardware address.  */
  unsigned short int ar_pro;              /* Format of protocol address.  */
  unsigned char ar_hln;                   /* Length of hardware address.  */
  unsigned char ar_pln;                   /* Length of protocol address.  */
  // -------------------------
  unsigned short int ar_op;               /* ARP opcode (command).  */
  unsigned char __ar_sha[6];              /* Sender hardware address.  */
  unsigned char __ar_sip[4];              /* Sender IP address.  */
  unsigned char __ar_tha[6];              /* Target hardware address.  */
  unsigned char __ar_tip[4];              /* Target IP address.  */
  // -------------------------
 };
 struct arp_packet
 {
  struct ether_header ethhdr;
  struct arp_header arphdr;
  unsigned char padding[18];              /* filled with 0 */
 };
 
 /* arp reply:
 *      op = 2
 *      ethhdr.ether_dhost = arphdr.__ar_tha = switch hard addr
 *      ethhdr.ether_shost = arphdr.__ar_sha = local hard addr
 *      arphdr.__ar_tip = switch ip
 *      arphdr.__ar_sip = victim ip
 */
#define FRAME_TYPE      0x0806                  /* arp=0x0806,rarp=0x8035 */
#define HARD_TYPE       1                       /* ethernet is 1 */
#define PROTO_TYPE      0x0800                  /* IP is 0x0800 */
#define OP_CODE         1                       /* arp=1/2,1为请求,2为应答,rarp=3/4 */
   

 
// linux下获取LAN里指定IP的网卡MAC
// In: argv[1]:本机IP,argv[2]:目的IP
// Out: 
int main( int argc, char *argv[] )
{
 string strETH;  // 本机NIC名称
 string strLocalMAC; // 本机MAC
 string strSrcIP; // 本机IP
 string strDesMAC; // 目的MAC
 string strDesIP; // 目的IP
 
 // 检查参数
 if ( argc != 4 )
 {
  printf("Useage: get_mac [interface name of the IP] [IP] [ARP IP]/n/n");
  return 0;
 }  
 strETH = argv[1]; //"eth0";
 strSrcIP = argv[2]; //"10.0.1.77";
 strDesIP = argv[3]; //"10.0.1.69";
 
 printf("Run ....../n");
 printf("获取 %s 接口的MAC ....../n", strETH.c_str());
 // 获取指定NIC名称的MAC
 strLocalMAC = GetLocalMac(strETH); 
#if 0
 printf("Note: %s[%s]/n", strETH.c_str(), strLocalMAC.c_str());
#endif
 
 // 获取指定接口MAC
 if ( 0 == strcmp( (const char*)strLocalMAC.c_str(), (const char*)"") )
 {
  printf("Error: call strcmp() failed/n");
  printf("--------------------------------/n/n");
  return -1;
 }
 else
 {
  printf("获取接口MAC成功: %s [%s]/n", strETH.c_str(), strLocalMAC.c_str()); 
 }
 
 // 获取指定IP网卡的MAC
 strDesMAC = GetMacByIP(strSrcIP, strLocalMAC, strDesIP, strETH);   
 printf("strDesMAC = %s/n", strDesMAC.c_str());
 // 
 return 0;
}


// 获取本地某网卡的MAC
// In: strEth
// Out: 若成功,返回MAC字符串,失败,返回""(空串)
static string GetLocalMac(string & strEth)
{
 string strLocalMAC;
 int s;
 struct ifreq buffer;
 char chBuff[MAX_MAC_LEN];
 
 memset(chBuff, 0x0, sizeof(chBuff));
 //arp_process(NULL);   
 s = socket(PF_INET, SOCK_DGRAM, 0); 
 if (-1 == s)
 {
  printf("Error: create socket failture/n");
  printf("--------------------------------/n/n");
  return "";
 }   
 memset(&buffer, 0x00, sizeof(buffer));    
 strcpy(buffer.ifr_name, strEth.c_str());  // "eth0"    
 if ( -1 == ioctl(s, SIOCGIFHWADDR, &buffer))
 {
  printf("Error: 获取接口 %S MAC 失败/n", strEth.c_str());
  printf("--------------------------------/n/n");
  return "";   
 }    
 close(s);
    
 for( s = 0; s < 6; s++ )
 {
  memset(chBuff, 0x0, sizeof(chBuff));
  sprintf( chBuff, "%.2X", (unsigned char)buffer.ifr_hwaddr.sa_data[s]);
  strLocalMAC += chBuff;
  
  //printf("%.2X", (unsigned char)buffer.ifr_hwaddr.sa_data[s]);
  if (s < 5)
  {
   memset(chBuff, 0x0, sizeof(chBuff));
   sprintf( chBuff, "%s", COMPART_MAC);
   strLocalMAC += chBuff;
   //printf(":");
  }
 }    
 //printf("/n");
    
 return strLocalMAC; 
}


//-------------------------------------------------------
// 发送ARP包,并接收ARP应答包,取出MAC
// In: strSrcIP:本机IP,strSrcMAC:本机IP的MAC,strDesIP:被请求应答MAC的IP , strNIC:本地接口名
// Out: 若成功,返回MAC,失败返回""(空串)
static string GetMacByIP(string strSrcIP, string strSrcMAC, string strDesIP ,string strNIC)
{
 int sockfd;     // socket handle
 struct arp_packet arp;  // arp 请求包
 struct arp_packet arpRes; // arp 应用答包
 struct sockaddr sa;   // eth
 
 char chSrcIP[24];
 char chDesIP[24];
 char chSrcMAC[24];
 char chNIC[8];    
 memset(chSrcIP, 0x00, sizeof(chSrcIP));
 memset(chDesIP, 0x00, sizeof(chDesIP));
 memset(chSrcMAC, 0x00, sizeof(chSrcMAC));
 memset(chNIC, 0x00, sizeof(chNIC));
 sprintf(chSrcIP, "%s",  strSrcIP.c_str());
 sprintf(chDesIP, "%s",  strDesIP.c_str());
 sprintf(chSrcMAC, "%s", strSrcMAC.c_str());
 sprintf(chNIC, "%s", strNIC.c_str()); 
 #define SRC_IP   chSrcIP  // 源IP
 #define DES_IP   chDesIP  // 目的IP
 #define LOCAL_HW        chSrcMAC // eth0的MAC 
 #define DEVICE   chNIC  // 本机接口名
  
 memset(&arp, 0x00, sizeof(arp));
 memset(&arpRes, 0x00, sizeof(arpRes));
 #if 1
 printf("源IP[%s]  源MAC[%s] 目的IP[%s]/n", /
   strSrcIP.c_str(), strSrcMAC.c_str(), strDesIP.c_str());  
 #endif
 
 sockfd = socket(AF_INET, SOCK_PACKET, htons(0x0806));
 if(sockfd < 0)
 {
  printf("Error: create socket failed/n");
  printf("--------------------------------/n/n");   
  return "";
 }
 
 /*
 // 设置socket为非阻塞模式
 if ( -1 != fcntl(sockfd, F_SETFL, O_NONBLOCK) )
 {
  printf("设置socket为非阻塞模式成功/n");
 }
 else
 {
  printf("Warning: 设置socket为非阻塞模式失败[errno = %d]/n", errno);
 }
 */
 
 // 设置socket接收超时
 struct timeval tv;
 tv.tv_sec = 0;
 tv.tv_usec= 100;
 if ( 0 == setsockopt( sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
 {
  printf("设置socket接收超时成功/n"); 
 }
 else
 {
  printf("Warning: 设置socket接收超时失败[errno = %d]/n", errno);
 }
 #if 1
 printf("创建socket SOCK_PACKET 成功/n");
 printf("Note: 创建ARP请求包 ....../n");
 printf("--------------------------------/n/n"); 
 #endif
 
 // 创建ARP请求包 
 /* init arp packet header */
 arp.ethhdr.ether_type = htons(FRAME_TYPE);
 set_hw_addr( (char *)arp.ethhdr.ether_dhost, DES_MAC );  
 set_hw_addr( (char *)arp.ethhdr.ether_shost, LOCAL_HW );
 #if 1
 printf("%x|", arp.ethhdr.ether_type);
 for (int i = 0; i < 6; i++)
 {
  printf("%d_", arp.ethhdr.ether_dhost[i]);  
 }
 printf("|");
 for (int i = 0; i < 6; i++)
 {
  printf("%d_", arp.ethhdr.ether_shost[i]);  
 } 
 printf("/n--------------------------------/n"); 
 printf("初始化ARP包帧头(以太网首部)成功/n/n");  
 #endif 
  
 /* init arp packet data */ 
 printf("初始化ARP包帧数据(ARP请求分组) ....../n"); 
 printf("--------------------------------/n"); 
 arp.arphdr.ar_hrd = htons(HARD_TYPE); // 1
 arp.arphdr.ar_pro = htons(PROTO_TYPE); // 0x0800
 arp.arphdr.ar_op = htons(OP_CODE);  // 1
 arp.arphdr.ar_hln = (unsigned char)(6);
 arp.arphdr.ar_pln = (unsigned char)(4);
 #if 1
 printf("%d|%d|%d|%d|%d|/n", arp.arphdr.ar_hrd, arp.arphdr.ar_pro, /
   arp.arphdr.ar_op, arp.arphdr.ar_hln, arp.arphdr.ar_pln);
 printf("--------------------------------/n");    
 #endif
 
 set_hw_addr((char *)arp.arphdr.__ar_tha, DES_MAC); // 请求IP的MAC 
 set_hw_addr((char *)arp.arphdr.__ar_sha, LOCAL_HW); // 发送者的MAC 
 set_ip_addr((char *)arp.arphdr.__ar_tip, DES_IP); // 请求MAC的IP 
 set_ip_addr((char *)arp.arphdr.__ar_sip, SRC_IP); // 源IP
 bzero(arp.padding, 18); // 填充18个字节
 #if 1 
 for (int i = 0; i < 6; i++)
 {
  printf("%d_", arp.arphdr.__ar_sha[i]);  
 }
 printf("|");
 for (int i = 0; i < 6; i++)
 {
  printf("%d_", arp.arphdr.__ar_sip[i]);  
 }
 printf("|"); 
 for (int i = 0; i < 6; i++)
 {
  printf("%d_", arp.arphdr.__ar_tha[i]);  
 }
 printf("|");

 for (int i = 0; i < 6; i++)
 {
  printf("%d_", arp.arphdr.__ar_tip[i]);  
 }
 printf("|");
 printf("/n--------------------------------/n");  
 #endif
  
 /* send arp reply packet */
 memset(&sa, 0x00, sizeof(sa));
 strcpy(sa.sa_data, DEVICE);
 
 // 发送ARP包
 int nSendCount = ARP_SEND_COUNT;
 while( (nSendCount --) > 0)
 {
  printf("发送ARP请求包[%d Bytes]...... [第%d个]/n", sizeof(arp), nSendCount);   
  if( sendto(sockfd, &arp, sizeof(arp), 0, (struct sockaddr*) &sa, sizeof(sa)) < 0 )
  {
   printf("Error: 发送ARP包失败 [errno = %d]/n", errno);
   return "";
  }
 }
 
 // 接收ARP应答包
 printf("NOte: 接收ARP应答 ....../n");
 int nTryCount = 5;
 int nRecvByte = 0;
 int nAddrLen = sizeof(sa);
 do
 {
  nRecvByte = recvfrom(sockfd, &arpRes, sizeof(arpRes),0, (struct sockaddr*)&sa, (socklen_t*)&nAddrLen); 
  
  // 若是所请求IP的ARP应答包,退出while
  string strTarIP;  /* Target IP address */
  if ( nRecvByte >= 60 && 2 == ntohs(arpRes.arphdr.ar_op) )
  {
   char chBuff[MAX_MAC_LEN];   
   string strTarIP;  /* Target IP address */
   // 格式化IP
   for (int s = 0; s < 4; s++)
   {
    memset(chBuff, 0x00, sizeof(chBuff));
    sprintf( (char *)chBuff, "%d", (unsigned char)arpRes.arphdr.__ar_sip[s]);
    strTarIP += chBuff;
    if (s < 3)
    {
     memset(chBuff, 0x00, sizeof(chBuff));
     sprintf( (char *)chBuff, "%s", ".");
     strTarIP += chBuff;
    }
   }
   if ( !strcmp(strTarIP.c_str(), strDesIP.c_str()) )
   {
    printf("/n请求IP[%s] = 应答IP[%s]/n", strDesIP.c_str(), strTarIP.c_str());
    break;
   }
  }
 }while( nTryCount -- ); // 接收ARP应答包的次数
 printf("已接收到ARP应答包 [%d Bytes]/n", nRecvByte);
 // 接收超时,或错误
 if ( nRecvByte == -1 )
 {
  printf("Warning: 接收超时,或计算机[%s]没有响应/n", strDesIP.c_str());
  close(sockfd);
  return "";
 }
 
 printf("分析ARP应答包 ....../n"); 
 char chBuff[MAX_MAC_LEN];   
 string strTarIP;  /* Target IP address */
 string strTarMAC;  /* Target hardware address */
 memset(chBuff, 0x00, sizeof(chBuff));
 // 格式化IP
 for (int s = 0; s < 4; s++)
 {
  memset(chBuff, 0x00, sizeof(chBuff));
  sprintf( (char *)chBuff, "%d", (unsigned char)arpRes.arphdr.__ar_sip[s]);
  strTarIP += chBuff;
  if (s < 3)
  {
   memset(chBuff, 0x00, sizeof(chBuff));
   sprintf( (char *)chBuff, "%s", ".");
   strTarIP += chBuff;
  }
 } 
 // 格式化MAC
 memset(chBuff, 0x00, sizeof(chBuff));
 for (int s = 0; s < 6; s++)
 {
  memset(chBuff, 0x00, sizeof(chBuff));
  sprintf( (char *)chBuff, "%02X", (unsigned char)arpRes.arphdr.__ar_sha[s]);
  strTarMAC += chBuff;
  if (s < 5)
  {
   memset(chBuff, 0x00, sizeof(chBuff));
   sprintf( (char *)chBuff, "%s", COMPART_MAC);
   strTarMAC += chBuff;
  }
 }
 // 输出目的IP,目的MAC  
 printf("应答IP[%s] 对应的MAC[%s]/n", strTarIP.c_str(), strTarMAC.c_str());
 printf("/n--------------------------------/n/n");
 close(sockfd); 
 // 返回被请求的MAC 
 return strTarMAC; 
 /* return */
}
    
    
// 填充MAC   
void set_hw_addr (char buf[], char *str)
{
              int i;
              char c, val;
              for(i = 0; i < 6; i++)
              {
                      if (!(c = tolower(*str++)))
                              perror("Invalid hardware address"),exit(1);
                     if (isdigit(c))
                             val = c - '0';
                     else if (c >= 'a' && c <= 'f')
                             val = c-'a'+10;
                     else
                             perror("Invalid hardware address"),exit(1);
                     buf[i] = val << 4;
                     if (!(c = tolower(*str++)))
                             perror("Invalid hardware address"),exit(1);
                     if (isdigit(c))
                             val = c - '0';
                     else if (c >= 'a' && c <= 'f')
                             val = c-'a'+10;
                     else
                             perror("Invalid hardware address"),exit(1);
                     buf[i] |= val;
                     if (*str == ':')
                             str++;
             }
}
 

// 填充IP
void set_ip_addr(char *buf, char *str)
{
  struct in_addr addr;
  memset(&addr, 0x00, sizeof(addr));
  addr.s_addr = inet_addr(str);  
  memcpy(buf, &addr, 4);
}

//-------------------------------------------------------


// end file

// --------------------------------------------------------------------------------------------------------------

# makefile

bin = get_mac
objets = main.o
rubbish = $(objets) $(bin)

$(bin) : main.o
 g++ -o $(bin) main.o

main.o : main.cpp all.h
 g++ -c main.cpp


.PHONY : clean
clean :
 -rm $(rubbish) 


# end makefile

 

/******************************************************************************/


/* 时光飞快流逝,2005年写的代码, 2005年是我工作2年后。7年后又可以重用, 我重新修改成C代码。*/

 

 

[cpp] view plaincopy  
  1. /******************************************************************************* 
  2. * File: main.c 
  3. * Description:  
  4. * Author: Xiaoyong Wen <wen_kernel@163.com>, 2005/06/20,a.m. 
  5. * 
  6. * Fix hisoty: 
  7. * v1.1.0    Xiaoyong Wen <wen_kernel@163.com>, 20130808, p.m., Reconstruct to c code 
  8. * 
  9. *******************************************************************************/  
  10.   
  11.   
  12. #define DEBUG   /* show debug info only */  
  13. #if defined(DEBUG)  
  14. #define wenxy_debug(fmt, args...) \  
  15.     printf(fmt, ##args)  
  16. #else  
  17. #define wenxy_debug(fmt, ...)   
  18. #endif  
  19.   
  20. #include <unistd.h>  
  21. #include <memory.h>  
  22. #include <stdio.h>  
  23. #include <stdlib.h>  
  24. #include <sys/ioctl.h>  
  25. #include <sys/types.h>  
  26. #include <sys/socket.h>  
  27. #include <net/if.h>  
  28. #include <string.h>  
  29. #include <errno.h>   
  30.   
  31. // ---------------------  
  32. // 创建ARP包的头文件  
  33. #include<netinet/in.h>  
  34. #include<arpa/inet.h>  
  35. /* #include<linux/if_ether.h> */     
  36. #include<ctype.h>  
  37. #include <fcntl.h>  
  38. // ---------------------  
  39.   
  40. #define MAX_MAC_LEN 24  // MAC字串缓冲区的最大长度(byte)  
  41. #define COMPART_MAC ":"  // MAC字串的分格符, Warnning:修改此宏,必须再修改源程序!!!  
  42.   
  43. #define MAX_BUF_LEN 128  
  44. static char strETH[MAX_BUF_LEN] = {0};      // 本机NIC名称  
  45. static char strLocalMAC[MAX_BUF_LEN] = {0}; // 本机MAC  
  46. static char strSrcIP[MAX_BUF_LEN] = {0};    // 本机IP  
  47. static char strDesMAC[MAX_BUF_LEN] = {0};   // 目的MAC  
  48. static char strDesIP[MAX_BUF_LEN] = {0};    // 目的IP  
  49.   
  50. static char strTarIP[MAX_BUF_LEN] = {0};  /* Target IP address */  
  51. static char strTarMAC[MAX_BUF_LEN] = {0};  /* Target hardware address */  
  52. static int find_ip_flag = 0;     /* 1 means find, 0 means not find */  
  53.   
  54.   
  55. // function declare  
  56. static char * GetLocalMac(char *strEth); // get loacl NIC's MAC  
  57. static void set_ip_addr(char *,char *);   // 填充IP  
  58. static void set_hw_addr(char buf[], char *str); // 填充MAC  
  59. static char * GetMacByIP(char *strSrcIP, char *strSrcMAC, char *strDesIP ,char *strNIC); // 获取指定IP的MAC  
  60. int arp_main( char *nic_name, char *nic_ip, char *des_ip);  
  61.   
  62. /* 
  63. #define SRC_IP   "10.0.1.77"   // 源IP 
  64. #define DES_IP   "10.0.1.35"   // 目的IP 
  65. #define LOCAL_HW        "00:C0:4C:39:0D:6F" // 10.0.1.77的eth0的MAC 
  66. #define DEVICE          "eth0"    // 接口 
  67. */  
  68. #define PADD_MAC  "00:00:00:00:00:00"   // 填充的MAC  
  69. #define DES_MAC   "FF:FF:FF:FF:FF:FF"   // 广播MAC  
  70. #define ARP_SEND_COUNT 3                // 发送ARP请求的ARP包的个数  
  71. #define RX_ARP_COUNT 3                  // rx count of ARP response  
  72. #define SLEEP_MAX_US (1000 * 100)       /* unit microsecond */  
  73.   
  74. struct ether_header  
  75. {  
  76.     unsigned char  ether_dhost[6];          /* destination eth addr */  
  77.     unsigned char  ether_shost[6];          /* source ether addr    */  
  78.     unsigned short ether_type;              /* packet type ID field */  
  79. };  
  80. struct arp_header  
  81. {  
  82.     unsigned short int ar_hrd;              /* Format of hardware address.  */  
  83.     unsigned short int ar_pro;              /* Format of protocol address.  */  
  84.     unsigned char ar_hln;                   /* Length of hardware address.  */  
  85.     unsigned char ar_pln;                   /* Length of protocol address.  */  
  86.     // -------------------------  
  87.     unsigned short int ar_op;               /* ARP opcode (command).  */  
  88.     unsigned char __ar_sha[6];              /* Sender hardware address.  */  
  89.     unsigned char __ar_sip[4];              /* Sender IP address.  */  
  90.     unsigned char __ar_tha[6];              /* Target hardware address.  */  
  91.     unsigned char __ar_tip[4];              /* Target IP address.  */  
  92.     // -------------------------  
  93. };  
  94.   
  95. struct arp_packet  
  96. {  
  97.     struct ether_header ethhdr;  
  98.     struct arp_header arphdr;  
  99.     unsigned char padding[18];              /* filled with 0 */  
  100. };  
  101.   
  102. /* arp reply: 
  103. *      op = 2 
  104. *      ethhdr.ether_dhost = arphdr.__ar_tha = switch hard addr 
  105. *      ethhdr.ether_shost = arphdr.__ar_sha = local hard addr 
  106. *      arphdr.__ar_tip = switch ip 
  107. *      arphdr.__ar_sip = victim ip 
  108. */  
  109. #define FRAME_TYPE      0x0806                  /* arp=0x0806,rarp=0x8035 */  
  110. #define HARD_TYPE       1                       /* ethernet is 1 */  
  111. #define PROTO_TYPE      0x0800                  /* IP is 0x0800 */  
  112. #define OP_CODE         1                       /* arp=1/2,1为请求,2为应答,rarp=3/4 */  
  113.   
  114.   
  115. int main( int argc, char *argv[] )  
  116. {  
  117.     // 检查参数  
  118.     if ( argc != 4 )  
  119.     {  
  120.         wenxy_debug("Useage: %s [interface name of the IP] [IP] [ARP IP]\n\n", argv[0]);  
  121.         return 0;  
  122.     }    
  123.   
  124.     return arp_main( argv[1], argv[2], argv[3] );  
  125. }  
  126.   
  127. // linux下获取LAN里指定IP的网卡MAC  
  128. // In: nic_name: 本地网卡名字, nic_ip:本机IP,des_ip:目的IP  
  129. // Out: 1表示获取MAC成功,des_ip已被使用, -1表示发生错误,0表示des_ip未使用  
  130. int arp_main( char *nic_name, char *nic_ip, char *des_ip)  
  131. {  
  132.     strcpy(strETH, nic_name); //"eth0";  
  133.     strcpy(strSrcIP, nic_ip); //"10.0.1.77";  
  134.     strcpy(strDesIP, des_ip); //"10.0.1.69";  
  135.       
  136.     wenxy_debug("Run ......\n");  
  137.     wenxy_debug("获取 %s 接口的MAC ......\n", strETH);  
  138.     // 获取指定NIC名称的MAC  
  139.     /*strLocalMAC = GetLocalMac(strETH);*/  
  140.     GetLocalMac(strETH);  
  141.       
  142. #if 0  
  143.     wenxy_debug("Note: %s[%s]\n", strETH, strLocalMAC);  
  144. #endif  
  145.       
  146.     // 获取指定接口MAC  
  147.     if ( 0 == strcmp( (const char*)strLocalMAC, (const char*)"") )  
  148.     {  
  149.         wenxy_debug("Error: call strcmp() failed\n");  
  150.         wenxy_debug("--------------------------------\n\n");  
  151.         return -1;  
  152.     }  
  153.     else  
  154.     {  
  155.         wenxy_debug("获取接口MAC成功: %s [%s]\n", strETH, strLocalMAC);  
  156.     }  
  157.       
  158.     // 获取指定IP网卡的MAC  
  159.     /*strDesMAC = GetMacByIP(strSrcIP, strLocalMAC, strDesIP, strETH);*/  
  160.     GetMacByIP(strSrcIP, strLocalMAC, strDesIP, strETH);  
  161.     wenxy_debug("strDesMAC = %s\n", strDesMAC);  
  162.     if(1 == find_ip_flag)  
  163.     {  
  164.         printf("Note:  strDesIP: %s,  strDesMAC: %s\n", strDesIP, strDesMAC);  
  165.         return 1;  
  166.     }  
  167.     else  
  168.     {  
  169.         printf("Note:  strDesIP: %s does not use\n", strDesIP);  
  170.         return 0;  
  171.     }  
  172. }  
  173.   
  174.   
  175. // 获取本地某网卡的MAC  
  176. // In: strEth  
  177. // Out: 若成功,返回MAC字符串,失败,返回""(空串)  
  178. static char * GetLocalMac(char *strEth)  
  179. {  
  180.     int s;  
  181.     struct ifreq buffer;  
  182.     char chBuff[MAX_MAC_LEN];  
  183.     unsigned int str_len = 0;  
  184.     unsigned int offset = 0;  
  185.       
  186.     memset(chBuff, 0x0, sizeof(chBuff));  
  187.     //arp_process(NULL);     
  188.     s = socket(PF_INET, SOCK_DGRAM, 0);   
  189.     if (-1 == s)  
  190.     {  
  191.         wenxy_debug("Error: create socket failture\n");  
  192.         wenxy_debug("--------------------------------\n\n");  
  193.         return "";  
  194.     }     
  195.     memset(&buffer, 0x00, sizeof(buffer));      
  196.     strcpy(buffer.ifr_name, strEth);  // "eth0"      
  197.     if ( -1 == ioctl(s, SIOCGIFHWADDR, &buffer))  
  198.     {  
  199.         wenxy_debug("Error: 获取接口 %s MAC 失败\n", strEth);  
  200.         wenxy_debug("--------------------------------\n\n");  
  201.         return "";     
  202.     }      
  203.     close(s);  
  204.   
  205.     offset = 0;  
  206.     for( s = 0; s < 6; s++ )  
  207.     {  
  208.         memset(chBuff, 0x0, sizeof(chBuff));  
  209.         sprintf( chBuff, "%.2X", (unsigned char)buffer.ifr_hwaddr.sa_data[s]);  
  210.         str_len = strlen(chBuff);  
  211.         memcpy(strLocalMAC + offset, chBuff, str_len);  
  212.         offset += str_len;  
  213.         //wenxy_debug("%.2X", (unsigned char)buffer.ifr_hwaddr.sa_data[s]);  
  214.         if (s < 5)  
  215.         {  
  216.             memset(chBuff, 0x0, sizeof(chBuff));  
  217.             sprintf( chBuff, "%s", COMPART_MAC);  
  218.             str_len = strlen(chBuff);  
  219.             memcpy(strLocalMAC + offset, chBuff, str_len);  
  220.             offset += str_len;  
  221.             //wenxy_debug(":");  
  222.         }  
  223.     }      
  224.     //wenxy_debug("\n");  
  225.     return strLocalMAC;   
  226. }  
  227.   
  228.   
  229. //-------------------------------------------------------  
  230. // 发送ARP包,并接收ARP应答包,取出MAC  
  231. // In: strSrcIP:本机IP,strSrcMAC:本机IP的MAC,strDesIP:被请求应答MAC的IP , strNIC:本地接口名  
  232. // Out: 若成功,返回MAC,失败返回""(空串)  
  233. static char * GetMacByIP(char *strSrcIP, char *strSrcMAC, char *strDesIP, char *strNIC)  
  234. {  
  235.     int sockfd;     // socket handle  
  236.     struct arp_packet arp;  // arp 请求包  
  237.     struct arp_packet arpRes; // arp 应用答包  
  238.     struct sockaddr sa;   // eth  
  239.       
  240.     char chSrcIP[24];  
  241.     char chDesIP[24];  
  242.     char chSrcMAC[24];  
  243.     char chNIC[8];  
  244.     unsigned int str_len = 0;  
  245.     unsigned int offset = 0;  
  246.     int i;  
  247.     int s;  
  248.     find_ip_flag = 0;  
  249.       
  250.     memset(chSrcIP, 0x00, sizeof(chSrcIP));  
  251.     memset(chDesIP, 0x00, sizeof(chDesIP));  
  252.     memset(chSrcMAC, 0x00, sizeof(chSrcMAC));  
  253.     memset(chNIC, 0x00, sizeof(chNIC));  
  254.     sprintf(chSrcIP, "%s",  strSrcIP);  
  255.     sprintf(chDesIP, "%s",  strDesIP);  
  256.     sprintf(chSrcMAC, "%s", strSrcMAC);  
  257.     sprintf(chNIC, "%s", strNIC);   
  258. #define SRC_IP   chSrcIP  // 源IP  
  259. #define DES_IP   chDesIP  // 目的IP  
  260. #define LOCAL_HW        chSrcMAC // eth0的MAC   
  261. #define DEVICE   chNIC  // 本机接口名  
  262.       
  263.     memset(&arp, 0x00, sizeof(arp));  
  264.     memset(&arpRes, 0x00, sizeof(arpRes));  
  265. #if 1  
  266.     wenxy_debug("源IP[%s]  源MAC[%s] 目的IP[%s]\n", strSrcIP, strSrcMAC, strDesIP);    
  267. #endif  
  268.       
  269.     sockfd = socket(AF_INET, SOCK_PACKET, htons(0x0806));  
  270.     if(sockfd < 0)  
  271.     {  
  272.         wenxy_debug("Error: create socket failed\n");  
  273.         wenxy_debug("--------------------------------\n\n");     
  274.         return "";  
  275.     }  
  276.       
  277.     /* 
  278.     // 设置socket为非阻塞模式 
  279.     if ( -1 != fcntl(sockfd, F_SETFL, O_NONBLOCK) ) 
  280.     { 
  281.     wenxy_debug("设置socket为非阻塞模式成功\n"); 
  282.     } 
  283.     else 
  284.     { 
  285.     wenxy_debug("Warning: 设置socket为非阻塞模式失败[errno = %d]\n", errno); 
  286.     } 
  287.     */  
  288.       
  289.     // 设置socket接收超时  
  290.     struct timeval tv;  
  291.     tv.tv_sec = 0;  
  292.     tv.tv_usec= 100;  
  293.     if ( 0 == setsockopt( sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )  
  294.     {  
  295.         wenxy_debug("设置socket接收超时成功\n");   
  296.     }  
  297.     else  
  298.     {  
  299.         wenxy_debug("Warning: 设置socket接收超时失败[errno = %d]\n", errno);  
  300.     }  
  301. #if 1  
  302.     wenxy_debug("创建socket SOCK_PACKET 成功\n");  
  303.     wenxy_debug("Note: 创建ARP请求包 ......\n");  
  304.     wenxy_debug("--------------------------------\n\n");   
  305. #endif  
  306.       
  307.     // 创建ARP请求包   
  308.     /* init arp packet header */  
  309.     arp.ethhdr.ether_type = htons(FRAME_TYPE);  
  310.     set_hw_addr( (char *)arp.ethhdr.ether_dhost, DES_MAC );    
  311.     set_hw_addr( (char *)arp.ethhdr.ether_shost, LOCAL_HW );  
  312. #if 1  
  313.     wenxy_debug("%x|", arp.ethhdr.ether_type);  
  314.     for (i = 0; i < 6; i++)  
  315.     {  
  316.         wenxy_debug("%d_", arp.ethhdr.ether_dhost[i]);    
  317.     }  
  318.     wenxy_debug("|");  
  319.     for (i = 0; i < 6; i++)  
  320.     {  
  321.         wenxy_debug("%d_", arp.ethhdr.ether_shost[i]);    
  322.     }   
  323.     wenxy_debug("\n--------------------------------\n");   
  324.     wenxy_debug("初始化ARP包帧头(以太网首部)成功\n\n");    
  325. #endif   
  326.       
  327.     /* init arp packet data */   
  328.     wenxy_debug("初始化ARP包帧数据(ARP请求分组) ......\n");   
  329.     wenxy_debug("--------------------------------\n");   
  330.     arp.arphdr.ar_hrd = htons(HARD_TYPE); // 1  
  331.     arp.arphdr.ar_pro = htons(PROTO_TYPE); // 0x0800  
  332.     arp.arphdr.ar_op = htons(OP_CODE);  // 1  
  333.     arp.arphdr.ar_hln = (unsigned char)(6);  
  334.     arp.arphdr.ar_pln = (unsigned char)(4);  
  335. #if 1  
  336.     wenxy_debug("%d|%d|%d|%d|%d|\n", arp.arphdr.ar_hrd, arp.arphdr.ar_pro,   
  337.         arp.arphdr.ar_op, arp.arphdr.ar_hln, arp.arphdr.ar_pln);  
  338.     wenxy_debug("--------------------------------\n");      
  339. #endif  
  340.       
  341.     set_hw_addr((char *)arp.arphdr.__ar_tha, DES_MAC); // 请求IP的MAC   
  342.     set_hw_addr((char *)arp.arphdr.__ar_sha, LOCAL_HW); // 发送者的MAC   
  343.     set_ip_addr((char *)arp.arphdr.__ar_tip, DES_IP); // 请求MAC的IP   
  344.     set_ip_addr((char *)arp.arphdr.__ar_sip, SRC_IP); // 源IP  
  345.     bzero(arp.padding, 18); // 填充18个字节  
  346. #if 1  
  347.     for (i = 0; i < 6; i++)  
  348.     {  
  349.         wenxy_debug("%d_", arp.arphdr.__ar_sha[i]);    
  350.     }  
  351.     wenxy_debug("|");  
  352.     for (i = 0; i < 6; i++)  
  353.     {  
  354.         wenxy_debug("%d_", arp.arphdr.__ar_sip[i]);    
  355.     }  
  356.     wenxy_debug("|");   
  357.     for (i = 0; i < 6; i++)  
  358.     {  
  359.         wenxy_debug("%d_", arp.arphdr.__ar_tha[i]);    
  360.     }  
  361.     wenxy_debug("|");  
  362.       
  363.     for (i = 0; i < 6; i++)  
  364.     {  
  365.         wenxy_debug("%d_", arp.arphdr.__ar_tip[i]);    
  366.     }  
  367.     wenxy_debug("|");  
  368.     wenxy_debug("\n--------------------------------\n");    
  369. #endif  
  370.       
  371.     /* send arp reply packet */  
  372.     memset(&sa, 0x00, sizeof(sa));  
  373.     strcpy(sa.sa_data, DEVICE);  
  374.       
  375.     // 发送ARP包  
  376.     int nSendCount = ARP_SEND_COUNT;  
  377.     int nRecvByte = 0;  
  378.     while( (nSendCount --) > 0)  
  379.     {  
  380.         wenxy_debug("发送ARP请求包[%d Bytes]...... [第%d个]\n", sizeof(arp), nSendCount);     
  381.         if( sendto(sockfd, &arp, sizeof(arp), 0, (struct sockaddr*) &sa, sizeof(sa)) < 0 )  
  382.         {  
  383.             wenxy_debug("Error: 发送ARP包失败 [errno = %d]\n", errno);  
  384.             return "";  
  385.         }  
  386.   
  387.         // 接收ARP应答包  
  388.         wenxy_debug("Note: 接收ARP应答 ......\n");  
  389.         int nTryCount = RX_ARP_COUNT;  
  390.         int nAddrLen = sizeof(sa);    
  391.         do  
  392.         {  
  393.             /* because network and host delay */  
  394.             usleep(SLEEP_MAX_US);  
  395.               
  396.             nRecvByte = recvfrom(sockfd, &arpRes, sizeof(arpRes),0, (struct sockaddr*)&sa, (socklen_t*)&nAddrLen);   
  397.           
  398.             // 若是所请求IP的ARP应答包,退出while  
  399.             if ( nRecvByte >= 60 && 2 == ntohs(arpRes.arphdr.ar_op) )  
  400.             {  
  401.                 char chBuff[MAX_MAC_LEN];     
  402.                 // 格式化IP  
  403.                 offset = 0;  
  404.                 for (s = 0; s < 4; s++)  
  405.                 {  
  406.                     memset(chBuff, 0x00, sizeof(chBuff));  
  407.                     sprintf( (char *)chBuff, "%d", (unsigned char)arpRes.arphdr.__ar_sip[s]);  
  408.                     //wenxy_debug("chBuff: %s\n", chBuff);  
  409.                     //strTarIP += chBuff;  
  410.                     str_len = strlen(chBuff);  
  411.                     memcpy(strTarIP + offset, chBuff, str_len);  
  412.                     offset += str_len;  
  413.                     if (s < 3)  
  414.                     {  
  415.                         memset(chBuff, 0x00, sizeof(chBuff));  
  416.                         sprintf( (char *)chBuff, "%s", ".");  
  417.                         //strTarIP += chBuff;  
  418.                         str_len = 1;  
  419.                         memcpy(strTarIP + offset, chBuff, str_len);  
  420.                         offset += str_len;  
  421.                     }  
  422.                 }  
  423.                   
  424.                 if ( !strcmp(strTarIP, strDesIP) )  
  425.                 {  
  426.                     wenxy_debug("\n请求IP[%s] = 应答IP[%s]\n", strDesIP, strTarIP);  
  427.                     find_ip_flag = 1; /* find ip */  
  428.                     goto analyse_arp_response;  
  429.                 }  
  430.             }  
  431.         }while( nTryCount -- ); // 接收ARP应答包的次数  
  432.     }  
  433.   
  434.     analyse_arp_response:  
  435.     wenxy_debug("已接收到ARP应答包 [%d Bytes]\n", nRecvByte);  
  436.     // 接收超时,或错误  
  437.     if ( nRecvByte == -1 )  
  438.     {  
  439.         wenxy_debug("Warning: 接收超时,或计算机[%s]没有响应\n", strDesIP);  
  440.         close(sockfd);  
  441.         return "";  
  442.     }  
  443.       
  444.     wenxy_debug("分析ARP应答包 ......\n");   
  445.     char chBuff[MAX_MAC_LEN];     
  446.     memset(chBuff, 0x00, sizeof(chBuff));  
  447.     // 格式化IP  
  448.     offset = 0;  
  449.     for (s = 0; s < 4; s++)  
  450.     {  
  451.         memset(chBuff, 0x00, sizeof(chBuff));  
  452.         sprintf( (char *)chBuff, "%d", (unsigned char)arpRes.arphdr.__ar_sip[s]);  
  453.         //strTarIP += chBuff;  
  454.         str_len = strlen(chBuff);  
  455.         memcpy(strTarIP + offset, chBuff, str_len);  
  456.         offset += str_len;  
  457.         if (s < 3)  
  458.         {  
  459.             memset(chBuff, 0x00, sizeof(chBuff));  
  460.             sprintf( (char *)chBuff, "%s", ".");  
  461.             //strTarIP += chBuff;  
  462.             str_len = strlen(chBuff);  
  463.             memcpy(strTarIP + offset, chBuff, str_len);  
  464.             offset += str_len;  
  465.         }  
  466.     }   
  467.     // 格式化MAC  
  468.     memset(chBuff, 0x00, sizeof(chBuff));  
  469.     offset = 0;  
  470.     for (s = 0; s < 6; s++)  
  471.     {  
  472.         memset(chBuff, 0x00, sizeof(chBuff));  
  473.         sprintf( (char *)chBuff, "%02X", (unsigned char)arpRes.arphdr.__ar_sha[s]);  
  474.         //strTarMAC += chBuff;  
  475.         str_len = strlen(chBuff);  
  476.         memcpy(strTarMAC + offset, chBuff, str_len);  
  477.         offset += str_len;  
  478.         if (s < 5)  
  479.         {  
  480.             memset(chBuff, 0x00, sizeof(chBuff));  
  481.             sprintf( (char *)chBuff, "%s", COMPART_MAC);  
  482.             //strTarMAC += chBuff;  
  483.             str_len = strlen(chBuff);  
  484.             memcpy(strTarMAC + offset, chBuff, str_len);  
  485.             offset += str_len;  
  486.         }  
  487.     }  
  488.     // 输出目的IP,目的MAC    
  489.     wenxy_debug("应答IP[%s] 对应的MAC[%s]\n", strTarIP, strTarMAC);  
  490.     wenxy_debug("\n--------------------------------\n\n");  
  491.     close(sockfd);   
  492.     // 返回被请求的MAC   
  493.     strcpy(strDesMAC, strTarMAC);  
  494.     /* return */          
  495.     return strDesMAC;   
  496. }  
  497.   
  498.   
  499. // 填充MAC    
  500. static void set_hw_addr (char buf[], char *str)  
  501. {  
  502.     int i;  
  503.     char c, val;  
  504.     for(i = 0; i < 6; i++)  
  505.     {  
  506.         if (!(c = tolower(*str++)))  
  507.             perror("Invalid hardware address"),exit(1);  
  508.         if (isdigit(c))  
  509.             val = c - '0';  
  510.         else if (c >= 'a' && c <= 'f')  
  511.             val = c-'a'+10;  
  512.         else  
  513.             perror("Invalid hardware address"),exit(1);  
  514.         buf[i] = val << 4;  
  515.         if (!(c = tolower(*str++)))  
  516.             perror("Invalid hardware address"),exit(1);  
  517.         if (isdigit(c))  
  518.             val = c - '0';  
  519.         else if (c >= 'a' && c <= 'f')  
  520.             val = c-'a'+10;  
  521.         else  
  522.             perror("Invalid hardware address"),exit(1);  
  523.         buf[i] |= val;  
  524.         if (*str == ':')  
  525.             str++;  
  526.     }  
  527. }  
  528.   
  529.   
  530. // 填充IP  
  531. static void set_ip_addr(char *buf, char *str)  
  532. {  
  533.     struct in_addr addr;  
  534.     memset(&addr, 0x00, sizeof(addr));  
  535.     addr.s_addr = inet_addr(str);    
  536.     memcpy(buf, &addr, 4);  
  537. }  
  538.   
  539. //-------------------------------------------------------  
  540.   
  541.   
  542. // end file  

 

[cpp] view plaincopy  
  1. ################################################################################  
  2. # File: Makefile  
  3. # Description:   
  4. # Author: Xiaoyong Wen <wen_kernel@163.com>, 20130807, AM.  
  5. #  
  6. # Fix hisoty:  
  7. #  
  8. ################################################################################  
  9.   
  10.   
  11. debug := 1  
  12. ifdef debug  
  13. CFLAGS += -g  
  14. else  
  15. CFLAGS += -O2  
  16. endif  
  17.   
  18. #CC := g++  
  19. CC := gcc  
  20.   
  21. target_bin := lan_mac_scan  
  22. bin := main  
  23. obj := main.o  
  24. #src := main.c  
  25. src := $(wildcard *.c) $(wildcard *.h)  
  26.   
  27. .PHONY : clean all debug  
  28.   
  29. all : $(bin)  
  30.     cp main $(target_bin)  
  31.     @-ls -l $(target_bin)  
  32.   
  33. $(bin) : $(obj)  
  34.   
  35. $(obj) : $(src)  
  36.   
  37.   
  38. debug:  
  39.     @echo $(src)  
  40.     @echo $(obj)  
  41.     @echo $(CFLAGS)   
  42.     @echo $(LDFLAGS)   
  43.   
  44. clean:    
  45.     rm -f $(bin) $(obj) $(target_bin)  

 

Useage: ./lan_mac_scan [interface name of the IP] [IP] [ARP IP]

#./lan_mac_scan 本地网卡名字 本地网卡的IP地址 检查是否使用的IP地址
例如:
#./lan_mac_scan eth0 172.22.0.26 172.22.0.25

注意事项:
1. Unix类操作系统的内核已支持packet socket。
2. 需要root权限。
3. 只能在LAN中使用,ARP包不能跨越router,除非router上有ARP proxy.
4. 如果本地机器或者远程机器安装有firewall,ARP包会被过滤而失效。

RFID管理系统集成商 RFID中间件 条码系统中间层 物联网软件集成

给我们留言

电话咨询
邮件咨询
在线地图
微信15622149977