linux用C++,如何用获取网口设备mac地址?
linux用C++,如何用获取网口设备mac地址? #include <sys/ioctl.h>#include <net/if.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>
void dump_macaddress(char* address) {
printf("%02x", address);
for (int i = 1; i < 6; i++) {
printf(":%2x", address & 0xff);
}
printf("\n");
}
int main() {
struct ifreq ifr;
struct ifconf ifc;
char buf;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock == -1) { /* handle error*/ };
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) { /* handle error */ }
struct ifreq *it = ifc.ifc_req;
const struct ifreq *const end = it + (ifc.ifc_len / sizeof(struct ifreq));
for (; it != end; ++it) {
strcpy(ifr.ifr_name, it->ifr_name);
if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
if (!(ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
dump_macaddress(ifr.ifr_hwaddr.sa_data);
}
}
} else { /* handle error */ }
}
} 请问如何只获取当前本机的MAC地址呢?上面的代码会把全部MAC地址都得到,包括虚拟网卡的地址
页:
[1]