Getting MAC address?

Doug Rabson dfr at nlsystems.com
Sat Jun 26 05:52:06 PDT 2004


On Saturday 26 June 2004 10:15, Ivan Voras wrote:
> Dmitry Morozovsky wrote:
> > On Sat, 26 Jun 2004, Ivan Voras wrote:
> >
> > IV> How to get the MAC address for an (ethernet) interface? The
> > linux code IV> does this:
> > IV> 	retval = ioctl(thisint->sockInt, SIOCGIFHWADDR, &ifr);
> > IV>
> > IV> After some searching, I found SIOCSIFLLADDR ioctl, but it
> > appears there IV> isn't a "GET" counterpart.
> > IV>
> > IV> (I've got interface name & index available...)
> >
> > Take a look at ifconfig(8) source.
> >
> > getifaddrs(3), case when sa_family == AF_LINK
>
> I was looking at it and came across getifaddrs(). This function does
> not depend on a open socket (yes, mine is AF_LINK, sockaddr_dl), and
> apparently returns a list of all interfaces. Is there really no other
> way than to traverse this list?

Its really not that hard:

static void
getNodeID(uint8_t node[6])
{
    struct ifaddrs *ifap;

    if (getifaddrs(&ifap) == 0) {
	struct ifaddrs *p;
	for (p = ifap; p; p = p->ifa_next) {
	    if (p->ifa_addr->sa_family == AF_LINK) {
		struct sockaddr_dl* sdp = (struct sockaddr_dl*) p->ifa_addr;
		memcpy(node, sdp->sdl_data + sdp->sdl_nlen, 6);
		freeifaddrs(ifap);
		return;
	    }
	}
	freeifaddrs(ifap);
    }
}


More information about the freebsd-hackers mailing list