MACアドレスを取得する(Windows/Linux/BSD(OSX))


getmacaddress.c

#include <stdio.h>


#if defined(WIN32) || (!defined(__GNUC__) && !defined(__clang__))
#include <winsock2.h>
#include <iphlpapi.h>
#include <stdlib.h>
#pragma comment(lib, "IPHLPAPI.lib")
#elif defined(__linux__)
#include <string.h> //strncpy
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#else
//bsd
#include <sys/types.h> //FreeBSD u_int
#include <ifaddrs.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_types.h>
#endif

void getmacaddress(char *mac_address){
#if defined(WIN32) || (!defined(__GNUC__) && !defined(__clang__))
//MSDNのサンプルコード
PIP_ADAPTER_INFO pAdapterInfo;
PIP_ADAPTER_INFO pAdapter;
ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
unsigned char *addr;

mac_address[0]=0;
pAdapterInfo = (IP_ADAPTER_INFO*)malloc(sizeof(IP_ADAPTER_INFO));
if(!pAdapterInfo)return;
if(GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW){
free(pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen);
if(!pAdapterInfo)return;
}

if(GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == NO_ERROR){
pAdapter = pAdapterInfo;
if(pAdapter){
addr = pAdapter->Address;
sprintf(mac_address,"%02x:%02x:%02x:%02x:%02x:%02x",
addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
}
}
free(pAdapterInfo);
#elif defined(__linux__)
//http://field-notes.hatenablog.jp/entry/20101216/1292467817
mac_address[0]=0;
struct ifreq *ifr, *ifend;
struct ifreq ifreq;
struct ifconf ifc;
struct ifreq ifs[16];
int fd;
unsigned char *addr;

fd = socket(AF_INET, SOCK_DGRAM, 0);
ifc.ifc_len = sizeof(ifs);
ifc.ifc_req = ifs;
if(ioctl(fd, SIOCGIFCONF, &ifc)<0){close(fd);return;}

ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
for(ifr = ifc.ifc_req;ifr < ifend;ifr++){
if(ifr->ifr_addr.sa_family == AF_INET){
strncpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
if(ioctl(fd, SIOCGIFHWADDR, &ifreq)<0)continue;
addr = ifreq.ifr_hwaddr.sa_data;
sprintf(mac_address,"%02x:%02x:%02x:%02x:%02x:%02x",
addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
}
}
close(fd);
#else
//bsd
mac_address[0]=0;
struct ifaddrs *ifa_list, *ifa;
struct sockaddr_dl *dl;
unsigned char *addr;
if(getifaddrs(&ifa_list)<0)return;
for(ifa = ifa_list;ifa;ifa = ifa->ifa_next){
dl = (struct sockaddr_dl*)ifa->ifa_addr;
if (dl->sdl_family == AF_LINK && dl->sdl_type == IFT_ETHER) {
addr = (unsigned char*)LLADDR(dl);
sprintf(mac_address,"%02x:%02x:%02x:%02x:%02x:%02x",
addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
return;
}
}
freeifaddrs(ifa_list);
#endif
}