Just a quick note for myself, and for anybody looking to do the
same. If you have an IP address and you want the corresponding MAC,
using the ARP cache, here is the function:
#include <stdio.h>
#include <sys/types.h>
#include <net/if_arp.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
void print_eth_addr(const char* ip)
{
int s;
struct sockaddr_in *sin;
struct arpreq a;
struct in_addr addr;
s = socket(AF_INET, SOCK_DGRAM,0);
memset(&a, 0, sizeof(a));
strcpy(a.arp_dev, "wlan0");
sin = (struct sockaddr_in*)&(a.arp_pa);
sin->sin_family = AF_INET;
a.arp_flags = ATF_PUBL;
inet_aton(ip, &addr);
memcpy(&sin->sin_addr, &addr, sizeof(struct in_addr));
if (ioctl(s,SIOCGARP,&a)) {
perror("ioctl");
}
unsigned char* hw_addr = (unsigned char *) a.arp_ha.sa_data;
printf("HWAddr found : %x:%x:%x:%x:%x:%x\n", hw_addr[0],
hw_addr[1], hw_addr[2], hw_addr[3], hw_addr[4], hw_addr[5]);
}
Just change “wlan0″ for “eth0″ or your favorite network interface.




