// Example output:
//
// Interface = en0 00:17:f2:0c:08:f4
// Interface = en1 00:17:f2:0c:08:f5
// Interface = vmnet1 00:50:56:c0:00:01
// Interface = vmnet8 00:50:56:c0:00:08
#include <iostream>
#include <sstream>
#include <iomanip>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <net/if_dl.h>
#include <net/if_types.h>
using namespace std;
int main (int argc, char * const argv[])
{
struct ifaddrs* p_ifaddrs = NULL;
struct sockaddr_dl* p_dl = NULL;
struct sockaddr* p_sockaddr = NULL;
unsigned char* ll_addr = NULL;
unsigned int i_val;
if (getifaddrs(&p_ifaddrs) < 0) {
cerr << "Could not get ifaddrs" << endl;
exit(-1);
}
while (p_ifaddrs != NULL) {
p_sockaddr = (struct sockaddr*)p_ifaddrs->ifa_addr;
if (p_sockaddr->sa_family == AF_LINK) {
p_dl = (struct sockaddr_dl*)p_sockaddr;
if (p_dl->sdl_type == IFT_ETHER) {
ostringstream os;
ll_addr = (unsigned char*)(p_dl->sdl_data + p_dl->sdl_nlen);
// Create string rep of ethernet address
for (int i = 0; i < p_dl->sdl_alen; i++) {
i_val = (unsigned int)(ll_addr[i]);
os << setw(2) << setfill('0') << hex << i_val;
if ((i+1) < p_dl->sdl_alen) {
os << ':';
}
}
// print string rep of interface name and ethernet address
cout << "Interface = " << setw(8) << p_ifaddrs->ifa_name
<< " " << os.str() << endl;
} // if (p_dl->sdl_type == IFT_ETHER)
} // if (p_sockaddr->sa_family == AF_LINK)
p_ifaddrs = p_ifaddrs->ifa_next;
} // while (p_ifaddrs != NULL)
return 0;
}