Advertisement
obernardovieira

Get Mac Adress using IP Adress

Apr 8th, 2014
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. //http://www.binarytides.com/get-mac-address-from-ip-in-winsock/
  2. /*
  3. Author: Silver Moon ( m00n.silv3r@gmail.com )
  4. Find mac address of a given IP address using iphlpapi
  5. */
  6.  
  7. #include "winsock2.h"
  8. #include "iphlpapi.h"   //For SendARP
  9. #include "stdio.h"
  10. #include "conio.h"
  11.  
  12. #pragma comment(lib , "iphlpapi.lib") //For iphlpapi
  13. #pragma comment(lib , "ws2_32.lib") //For winsock
  14.  
  15. void GetMacAddress(unsigned char * , struct in_addr );
  16.  
  17. int main()
  18. {
  19.     unsigned char mac[6];
  20.     struct in_addr srcip;
  21.     char ip_address[32];
  22.  
  23.     WSADATA firstsock;
  24.      
  25.     if (WSAStartup(MAKEWORD(2,2),&firstsock) != 0)
  26.     {
  27.         printf("\nFailed to initialise winsock.");
  28.         printf("\nError Code : %d" , WSAGetLastError() );
  29.         return 1;
  30.     }
  31.      
  32.     //Ask user to select the device he wants to use
  33.     printf("Enter the ip address : ");
  34.     scanf_s("%s",ip_address);
  35.     srcip.s_addr = inet_addr(ip_address);
  36.  
  37.     //Get mac addresses of the ip
  38.     GetMacAddress(mac , srcip);
  39.     printf("Selected device has mac address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
  40.     printf("\n");
  41.      
  42.     _getch();
  43.     return 0;
  44. }
  45.  
  46. /*
  47.     Get the mac address of a given ip
  48. */
  49. void GetMacAddress(unsigned char *mac , struct in_addr destip)
  50. {
  51.     DWORD ret;
  52.     IPAddr srcip;
  53.     ULONG MacAddr[2];
  54.     ULONG PhyAddrLen = 6;  /* default to length of six bytes */
  55.     int i;
  56.  
  57.     srcip = 0;
  58.  
  59.     //Send an arp packet
  60.     ret = SendARP((IPAddr) destip.S_un.S_addr , srcip , MacAddr , &PhyAddrLen);
  61.      
  62.     //Prepare the mac address
  63.     if(PhyAddrLen)
  64.     {
  65.         BYTE *bMacAddr = (BYTE *) & MacAddr;
  66.         for (i = 0; i < (int) PhyAddrLen; i++)
  67.         {
  68.             mac[i] = (char)bMacAddr[i];
  69.         }
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement