frkang

博客园 首页 联系 订阅 管理

代码如下:

 1 #include "winsock2.h"
 2 #include "iphlpapi.h"   //For SendARP
 3 #include "stdio.h"
 4 #include "conio.h"
 5  
 6 #pragma comment(lib , "iphlpapi.lib") //For iphlpapi
 7 #pragma comment(lib , "ws2_32.lib") //For winsock
 8  
 9 void GetMacAddress(unsigned char * , struct in_addr );
10  
11 int main() 
12 {
13     unsigned char mac[6];
14     struct in_addr srcip;
15     char ip_address[32];
16  
17     WSADATA firstsock;
18      
19     if (WSAStartup(MAKEWORD(2,2),&firstsock) != 0) 
20     {
21         printf("\nFailed to initialise winsock.");
22         printf("\nError Code : %d" , WSAGetLastError() );
23         return 1;
24     }
25      
26     //Ask user to select the device he wants to use
27     printf("Enter the ip address : ");
28     scanf("%s",ip_address);
29     srcip.s_addr = inet_addr(ip_address);
30  
31     //Get mac addresses of the ip
32     GetMacAddress(mac , srcip);
33     printf("Selected device has mac address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
34     printf("\n");
35     printf("Press any key to exit\n");
36      
37     _getch();
38     return 0;
39 }
40  
41 /*
42     Get the mac address of a given ip
43 */
44 void GetMacAddress(unsigned char *mac , struct in_addr destip)
45 {
46     DWORD ret;
47     IPAddr srcip;
48     ULONG MacAddr[2];
49     ULONG PhyAddrLen = 6;  /* default to length of six bytes */
50     int i;
51  
52     srcip = 0;
53  
54     //Send an arp packet
55     ret = SendARP((IPAddr) destip.S_un.S_addr , srcip , MacAddr , &PhyAddrLen);
56      
57     //Prepare the mac address
58     if(PhyAddrLen)
59     {
60         BYTE *bMacAddr = (BYTE *) & MacAddr;
61         for (i = 0; i < (int) PhyAddrLen; i++)
62         {
63             mac[i] = (char)bMacAddr[i];
64         }
65     }
66 }

 

posted on 2013-11-28 08:59  frkang  阅读(586)  评论(0编辑  收藏  举报