美文网首页
获取电脑mac地址

获取电脑mac地址

作者: 863cda997e42 | 来源:发表于2022-06-22 10:59 被阅读0次

获取电脑mac地址

#include <iostream>
#include <ifaddrs.h>
#include <sys/socket.h>
#include <net/if_dl.h>

void getMacAddress(char *mac, const char *name = "en0"){
    
    struct ifaddrs * iflist = NULL;
    if(getifaddrs(&iflist) == 0){
        for(struct ifaddrs *cur = iflist; cur; cur = cur->ifa_next){
            if((cur->ifa_addr->sa_family == AF_LINK) && !strcmp(cur->ifa_name,name)){
                sockaddr_dl *sdl = (sockaddr_dl *)cur->ifa_addr;
                sprintf(mac,"%02X:%02X:%02X:%02X:%02X:%02X",(unsigned char)LLADDR(sdl)[0],(unsigned char)LLADDR(sdl)[1],
                        (unsigned char)LLADDR(sdl)[2],(unsigned char)LLADDR(sdl)[3],(unsigned char)LLADDR(sdl)[4],
                        (unsigned char)LLADDR(sdl)[5]);
            }
        }
    }
    if (iflist) {
        freeifaddrs(iflist);
        iflist = NULL;
    }
}

char macAddress[20];

int main(int argc, const char * argv[]) {
    
    getMacAddress(macAddress);
    printf("%s\n", macAddress);
    getMacAddress(macAddress, "en1");
    printf("%s\n", macAddress);
    return 0;
}

AC:87:A3...
60:F8:1D...

相关文章

网友评论

      本文标题:获取电脑mac地址

      本文链接:https://www.haomeiwen.com/subject/psayvrtx.html