/*
 * get_mac_address.c
 *
 * get the mac address of an interface and print it out.
 * 
 * Code blatantly borrowed from dhcpd. 
 * 
 * Only tested on FreeBSD.
 *
 * Steve Shah (sshah@planetoid.org)
 *
 */

#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <ctype.h>
#include <time.h>
#include <sys/socket.h>
#include <net/if_types.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <net/if_dl.h>

void getmac(char *devname)
{
    struct ifconf ic;
    struct ifreq ifr;
    int sock;
    char buf[8192];
    unsigned char buf2[128];
    int j;
    int i;

    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
	perror ("Can't create socket");
	return;
    }

    ic.ifc_len = sizeof(buf);
    ic.ifc_ifcu.ifcu_buf = (caddr_t)buf;
    i = ioctl(sock, SIOCGIFCONF, &ic);

    if (i < 0) {
	perror ("ioctl: SIOCGIFCONF");
	return;
    }

    for (i = 0; i < ic.ifc_len;) {
	struct ifreq *ifp = (struct ifreq *)((caddr_t)ic.ifc_req + i);
	i += sizeof (*ifp);

	strcpy (ifr.ifr_name, ifp->ifr_name);
	if (strcmp(ifr.ifr_name,devname)) continue;

	if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
	    printf ("Can't get interface flags for %s: ", ifr.ifr_name);
	    fflush(stdout);
	    perror("");
	    return;
	}

	printf ("%s: ",ifp->ifr_name);
	fflush(stdout);

	if (ifp->ifr_addr.sa_family == AF_LINK) {
	    struct sockaddr_dl *foo = (struct sockaddr_dl *)(&ifp->ifr_addr);
	    memcpy(buf2,LLADDR(foo), foo->sdl_alen);
	    for (j=0; j<foo->sdl_alen; j++) {
		printf ("%02x",buf2[j]);
		if (j < (foo->sdl_alen - 1)) printf (":");
	    }
	    printf ("\n");
	}
    }
}

	    
    

int main ()
{
    getmac("dc0");
    return 0;
}





