1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| int get_if_macaddr(const char *name, char *macaddr) { int ret; int rc; int sockfd; unsigned char mac[6]; struct ifreq ifr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { printf("socket() failed, err: %d,[%s]\n", errno, strerror(errno)); return -1; }
snprintf(ifr.ifr_name, (sizeof(ifr.ifr_name) - 1), "%s", name);
rc = ioctl(sockfd, SIOCGIFFLAGS, &ifr); if (rc < 0) { printf("ioctl(%s, SIOCGIFFLAGS) failed, err: %d,[%s]\n", name, errno, strerror(errno)); ret = -1; goto out; }
rc = ioctl(sockfd, SIOCGIFHWADDR, &ifr); if (rc < 0) { printf("ioctl(%s, SIOCGIFHWADDR, %s) failed, err: %d,[%s]\n", name, macaddr, errno, strerror(errno)); ret = -1; goto out; }
memcpy(mac, ifr.ifr_hwaddr.sa_data, sizeof(mac)); sprintf(macaddr, "%02X:%02X:%02X:%02X:%02X:%02X", (unsigned char)mac[0], (unsigned char)mac[1], (unsigned char)mac[2], (unsigned char)mac[3], (unsigned char)mac[4], (unsigned char)mac[5]); ret = 0;
out: if (sockfd >= 0) { close(sockfd); }
return (ret); }
|