Tuesday, September 29, 2009

Read ARP entry Linux

/******************************************************
Author : Chaitu
Date : 29/09/2009
Description : Reading MAC address from kernel arp table
in Linux
*******************************************************/
#include "sys/types.h"
#include "sys/socket.h"
#include "sys/time.h"
#include "sys/ioctl.h"
#include "net/route.h"
#include "stdio.h"
#include "errno.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"
#include "arpa/inet.h"
#include "netinet/ether.h"
#include "netpacket/packet.h"
#include "net/if.h"

int main(int argc, char **argv)
{
struct sockaddr_in *sin;
struct arpreq myreq;
int sockfd;

if(argc != 3)
{
printf("Usage:./mac \n");
exit(1);
}
/* Initialize the structure */
memset(&myreq, '\0', sizeof(myreq));

/* AF_INET family is must */
sin = (struct sockaddr_in *)&myreq.arp_pa;
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = inet_addr(argv[2]); // Give the IP for which MAC is needed

sin = (struct sockaddr_in *)&myreq.arp_ha;
sin->sin_family = AF_INET;

memcpy(myreq.arp_dev,argv[1],IFNAMSIZ - 1);

/* Open socket for IOCTL operation */
if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("socket");
exit(1);
}

/* IOCTL for accessing the MAC address */
if((ioctl(sockfd, SIOCGARP,&myreq, sizeof(myreq)) < 0))
{
perror("ioctl");
close(sockfd);
exit(1);
}

printf("mac address of IP:%s is %02x:%02x:%02x:%02x:%02x:%02x\n", argv[2],( myreq.arp_ha.sa_data[0]&0xFF),
(myreq.arp_ha.sa_data[1]&0xFF),
(myreq.arp_ha.sa_data[2]&0xFF),
(myreq.arp_ha.sa_data[3]&0xFF),
(myreq.arp_ha.sa_data[4]&0xFF),
(myreq.arp_ha.sa_data[5]&0xFF));

return 0;
}