获取电脑mac地址

获取电脑mac地址

#include 
#include 
#include 
#include 

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地址)