getting interface MAC addr from C

Michal Mertl mime at traveller.cz
Fri Aug 4 16:16:17 UTC 2006


Mario Lobo wrote:
> Hi;
> 
> Would anyone have a tip on how to get the MAC from a C program?
> 
> I tried:
> 
>     struct ifreq ifreq;
>     unsigned char *hw;
> 
>     strcpy(ifreq.ifr_name, "rl0");
>     ioctl(fd, SIOCGIFMAC, &ifreq);
>     hw = ifreq.ifr_ifru.ifru_data; ????

This is probably very far from what you want. MAC stands here for MAC(4)
- e.g. security related stuff as opposed to something network (did you
read MAC as Media Access Control?).

I don't know it that is the easiest/right way to get this information
but you can use getifaddrs(3). Attached find a simple program which
prints out the interfaces and their MAC addresses using getifaddrs().
The code for getting the printable address is taken from function
fmt_sockaddr() from src/usr.bin/netstat/route.c.

You can also probably use SIOCGIFADDR with the right socket passed in as
fd or with sysctl(3) (int mib[] = { CTL_NET, AF_ROUTE, 0, AF_LINK,
NET_RT_IFLIST, 0}).

> but i don't know if this is right or, if it is, where to get the MAC from the 
> structure. I doesn't issue any error compiling or running though.
> 
> In linux i used:
> 
>     struct ifreq ifreq;
>     unsigned char *hw;
> 
>     strcpy(ifreq.ifr_name, "rl0");
>     ioctl(fd, SIOCGIFHWADDR, &ifreq);
>     hw = ifreq.ifr_hwaddr.sa_data;
> 
> Thanks,
> 
> Mario
> 

HTH

Michal


More information about the freebsd-hackers mailing list