首页 > 代码库 > [记]Linux 获取本机(全部)IP、MAC地址方法 (C/C++)

[记]Linux 获取本机(全部)IP、MAC地址方法 (C/C++)

Linux 获取本机IP、MAC地址用法大全

 

 1    2 //#include <sys/types.h> 3 #include <ifaddrs.h> 4 #include <sys/ioctl.h>  5 #include <net/if.h>  6 #include <string.h>  7 #include <stdio.h> 8 #include <unistd.h> 9 #include <netdb.h>10 //#include <sys/socket.h>11 //#include <netinet/in.h>12 #include <arpa/inet.h>13 14 char* getMac(char* mac,char* dv){15     struct   ifreq   ifreq; 16     int   sock; 17     if(!mac || !dv)18         return mac;19     if((sock=socket(AF_INET,SOCK_STREAM,0)) <0) 20     { 21         perror( "socket "); 22         return mac; 23     } 24     strcpy(ifreq.ifr_name,dv); 25     if(ioctl(sock,SIOCGIFHWADDR,&ifreq) <0) 26     { 27         perror( "ioctl "); 28         return mac; 29     } close(sock);30     sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x", 31            (unsigned char)ifreq.ifr_hwaddr.sa_data[0], 32            (unsigned char)ifreq.ifr_hwaddr.sa_data[1], 33            (unsigned char)ifreq.ifr_hwaddr.sa_data[2], 34            (unsigned char)ifreq.ifr_hwaddr.sa_data[3], 35            (unsigned char)ifreq.ifr_hwaddr.sa_data[4], 36            (unsigned char)ifreq.ifr_hwaddr.sa_data[5]);37     return mac;38 }39 40 int main (int argc, const char * argv[])41 {42     char hname[128];43     struct hostent *hent;44     int i;45 46     gethostname(hname, sizeof(hname));47 48     //hent = gethostent();49     hent = gethostbyname(hname);50 51     printf("hostname: %s\n", hent->h_name);52   53 //----------------------------------------------------------54     printf("\n\n\n");55 56     char mac[30];57     struct ifaddrs * ifAddrStruct=NULL;58     void * tmpAddrPtr=NULL;59 60     getifaddrs(&ifAddrStruct);61 62     while (ifAddrStruct!=NULL) {63         if (ifAddrStruct->ifa_addr->sa_family==AF_INET) { // check it is IP464             // is a valid IP4 Address65             tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;66             char addressBuffer[INET_ADDRSTRLEN];67             inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);68             printf("%s IP: %s\n", ifAddrStruct->ifa_name, addressBuffer);69             printf("MAC: %s\n\n",getMac(mac,ifAddrStruct->ifa_name));70         } else if (ifAddrStruct->ifa_addr->sa_family==AF_INET6) { // check it is IP671             // is a valid IP6 Address72             tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;73             char addressBuffer[INET6_ADDRSTRLEN];74             inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);75             printf("%s IP: %s\n", ifAddrStruct->ifa_name, addressBuffer); 76             printf("MAC: %s\n\n",getMac(mac,ifAddrStruct->ifa_name));77         } 78         ifAddrStruct=ifAddrStruct->ifa_next;79     }80     return 0;81 82 } 

 

再次做个笔记

(更多参考:Linux 获取本机IP、MAC地址用法大全)

 

[记]Linux 获取本机(全部)IP、MAC地址方法 (C/C++)