1

I'm looking for how to programmatically (in C/C++/etc.) obtain this kind of information:

# netstat -g
Link-layer Multicast Group Memberships
Group                   Link-layer Address  Netif
1:80:c2:0:0:3           <none>              en0
33:33:ff:c7:9c:2f       <none>              en1
1:0:5e:0:0:fb           <none>              en1
33:33:0:0:0:fb          <none>              en1
1:0:5e:0:0:1            <none>              en1

... and so on ...

On Linux I can get it from the /proc filesystem, but a lot of searching turns up nothing informative about OSX. I suspect it might be a sysctl() thing, but I have found nothing about which sysctl() requests to use.

1 Answer 1

2

I believe I have found the answer after a lot of searching. I finally found the source to Darwin's netstat, and it led me to this function. Type:

man getifmaddrs

Looks like it's the one. Also looks like it's the one for other BSDs.

Here is some sample code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if_dl.h>
#include <ifaddrs.h>

int main(int argc,char **argv)
{
  struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
  struct ifmaddrs *p;
  char name[32];
  unsigned char mac[6];

  if (!getifmaddrs(&ifmap)) {
    p = ifmap;
    while (p) {
      if (p->ifma_addr->sa_family == AF_LINK) {
        struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
        struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
        if (la->sdl_alen == 6) {
          memcpy(name,in->sdl_data,in->sdl_nlen);
          name[in->sdl_nlen] = 0;
          memcpy(mac,la->sdl_data + la->sdl_nlen,6);
          printf("%s %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",name,mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
        }
      }
      p = p->ifma_next;
    }
    freeifmaddrs(ifmap);
  }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.