#include <errno.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if_arp.h>
#include <netinet/in.h>
#include <linux/sockios.h>
#include <string.h>
#include <stdlib.h>

void show_mac(char *mac_bin)
{
	printf("%02X:%02X:%02X:%02X:%02X:%02X",
	       (mac_bin[0] & 0x00FF), (mac_bin[1] & 0x00FF),
	       (mac_bin[2] & 0x00FF), (mac_bin[3] & 0x00FF),
	       (mac_bin[4] & 0x00FF), (mac_bin[5] & 0x00FF));
	printf("\n");
}

static unsigned char *get_mac_arpcache(char *ip_str, char *iface)
{
	int s;
	struct arpreq areq;
	struct sockaddr_in *sin;
	struct in_addr ipaddr;

	/* static unsigned char *mac_bin = (unsigned char *) areq.arp_ha.sa_data; */
	static unsigned char *mac_bin;
	mac_bin = (unsigned char *)areq.arp_ha.sa_data;

	/* Get an internet domain socket. */
	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
		perror("socket");
		exit(1);
	}

	/* Make the ARP request. */
	memset(&areq, 0, sizeof(areq));
	sin = (struct sockaddr_in *)&areq.arp_pa;
	sin->sin_family = AF_INET;

	if (inet_aton(ip_str, &ipaddr) == 0) {
		fprintf(stderr, "-- Error: invalid IP address %s.\n", ip_str);
		exit(1);
	}

	sin->sin_addr = ipaddr;
	sin = (struct sockaddr_in *)&areq.arp_ha;
	sin->sin_family = ARPHRD_ETHER;

	strncpy(areq.arp_dev, iface, 15);

	if (ioctl(s, SIOCGARP, (caddr_t) & areq) == -1) {
		perror("-- Error: unable to make ARP request, error");
		exit(1);
	}

	return mac_bin;
}

int main(void)
{
	char *ip = "172.16.0.10";
	char *iface = "eth1";
	unsigned char *mac_bin;

	mac_bin = get_mac_arpcache(ip, iface);
	show_mac(mac_bin);

	return 0;
}