获取mac地址
#include <ifaddrs.h> #include <sys/ioctl.h> #include <net/if.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <netdb.h> #include <arpa/inet.h> char* getMac(char* mac,char* dv){ struct ifreq ifreq; int sock; if(!mac || !dv) return mac; if((sock=socket(AF_INET,SOCK_STREAM,0)) <0) { perror( "socket "); return mac; } strcpy(ifreq.ifr_name,dv); if(ioctl(sock,SIOCGIFHWADDR,&ifreq) <0) { perror( "ioctl "); return mac; } close(sock); sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x", (unsigned char)ifreq.ifr_hwaddr.sa_data[0], (unsigned char)ifreq.ifr_hwaddr.sa_data[1], (unsigned char)ifreq.ifr_hwaddr.sa_data[2], (unsigned char)ifreq.ifr_hwaddr.sa_data[3], (unsigned char)ifreq.ifr_hwaddr.sa_data[4], (unsigned char)ifreq.ifr_hwaddr.sa_data[5]); return mac; } int main (int argc, const char * argv[]) { char hname[128]; struct hostent *hent; int i; gethostname(hname, sizeof(hname)); //hent = gethostent(); hent = gethostbyname(hname); printf(" "); char mac[30]; struct ifaddrs * ifAddrStruct=NULL; void * tmpAddrPtr=NULL; getifaddrs(&ifAddrStruct); while (ifAddrStruct!=NULL) { if (ifAddrStruct->ifa_addr->sa_family==AF_INET) { // check it is IP4 // is a valid IP4 Address tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr; char addressBuffer[INET_ADDRSTRLEN]; inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); printf("%s IP: %s ", ifAddrStruct->ifa_name, addressBuffer); printf("MAC: %s ",getMac(mac,ifAddrStruct->ifa_name)); } else if (ifAddrStruct->ifa_addr->sa_family==AF_INET6) { // check it is IP6 // is a valid IP6 Address tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr; char addressBuffer[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN); printf("%s IP: %s ", ifAddrStruct->ifa_name, addressBuffer); printf("MAC: %s ",getMac(mac,ifAddrStruct->ifa_name)); } ifAddrStruct=ifAddrStruct->ifa_next; } return 0; }