NIC の MAC address を取得することに成功
NIC の MAC address を取得するも失敗 - Shammerismの文字化け調査で、ioctl request to get the HW addressを発見。ここの08-12-2003のコードでうまくいった。
#include <arpa/inet.h> #include <errno.h> #include <linux/if_ether.h> #include <net/if.h> // ifr #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> // ioctl #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> // close // http://cboard.cprogramming.com/linux-programming/43261-ioctl-request-get-hw-address.html void print_mac_address(const struct ifreq ifreq){ printf("Device %s -> Ethernet %02x:%02x:%02x:%02x:%02x:%02x\n", ifreq.ifr_name, (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[0], (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[1], (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[2], (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[3], (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[4], (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[5]); } int main(int argc, char **args){ int fd, status, i; struct ifreq ifr; fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); if( fd < 0 ){ perror("socket() failed.\n"); exit(EXIT_FAILURE); } // Access to NIC and get information memset(&ifr, 0, sizeof(ifr)); snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", args[1]); status = ioctl(fd, SIOCGIFHWADDR, &ifr); if( status < 0 ){ perror("ioctl() failed to get source MAC address.\n"); exit(EXIT_FAILURE); } close(fd); print_mac_address(ifr); return 0; }