[记]WIndow/Linux 获取本机(全部)IPv4、IPv6、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 void pHx(unsigned char* p,int len){ 14 printf("Hex: "); 15 for(int i=0;i<len;i++){ 16 printf("%02X:",p[i]); 17 } 18 printf("\b\n"); 19 } 20 char* getMac(char* mac,char* dv){ 21 struct ifreq ifreq; 22 int sock; 23 if(!mac || !dv) 24 return mac; 25 if((sock=socket(AF_INET,SOCK_STREAM,0)) <0) 26 { 27 perror( "socket "); 28 return mac; 29 } 30 strcpy(ifreq.ifr_name,dv); 31 if(ioctl(sock,SIOCGIFHWADDR,&ifreq) <0) 32 { 33 perror( "ioctl "); 34 return mac; 35 } 36 pHx((unsigned char*)ifreq.ifr_hwaddr.sa_data,sizeof(ifreq.ifr_hwaddr.sa_data)); 37 sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", //以太网MAC地址的长度是48位 38 (unsigned char)ifreq.ifr_hwaddr.sa_data[0], 39 (unsigned char)ifreq.ifr_hwaddr.sa_data[1], 40 (unsigned char)ifreq.ifr_hwaddr.sa_data[2], 41 (unsigned char)ifreq.ifr_hwaddr.sa_data[3], 42 (unsigned char)ifreq.ifr_hwaddr.sa_data[4], 43 (unsigned char)ifreq.ifr_hwaddr.sa_data[5]); 44 return mac; 45 } 46 47 int main (int argc, const char * argv[]) 48 { 49 char hname[128]; 50 struct hostent *hent; 51 int i; 52 53 gethostname(hname, sizeof(hname)); 54 55 //hent = gethostent(); 56 hent = gethostbyname(hname); 57 58 printf("hostname: %s\n", hent->h_name); 59 //---------------------------------------------------------- 60 printf("\n\n"); 61 62 char mac[30]; 63 struct ifaddrs * ifap0=NULL,*ifap=NULL; 64 void * tmpAddrPtr=NULL; 65 66 getifaddrs(&ifap0); 67 ifap=ifap0; 68 while (ifap!=NULL) { 69 if (ifap->ifa_addr->sa_family==AF_INET) { // check it is IP4 70 // is a valid IP4 Address 71 tmpAddrPtr=&((struct sockaddr_in *)ifap->ifa_addr)->sin_addr; 72 char addressBuffer[INET_ADDRSTRLEN]; 73 inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); 74 if(strcmp(addressBuffer,"127.0.0.1")!=0){ 75 printf("%s IPv4: %s\n", ifap->ifa_name, addressBuffer); 76 printf("MAC: %s\n\n",getMac(mac,ifap->ifa_name)); 77 } 78 } else if (ifap->ifa_addr->sa_family==AF_INET6) { // check it is IP6 79 // is a valid IP6 Address 80 tmpAddrPtr=&((struct sockaddr_in *)ifap->ifa_addr)->sin_addr; 81 char addressBuffer[INET6_ADDRSTRLEN]; 82 inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN); 83 if(strcmp(addressBuffer,"::")!=0){ 84 printf("%s IPv6: %s\n", ifap->ifa_name, addressBuffer); 85 printf("MAC: %s\n\n",getMac(mac,ifap->ifa_name)); 86 } 87 } 88 ifap=ifap->ifa_next; 89 } 90 if (ifap0) { freeifaddrs(ifap0); ifap0 = NULL; } 91 return 0; 92 }
输出:
hostname: localhost
eth0 IPv4: 192.168.42.2 MAC: 02:42:c0:a8:2a:02 eth0 IPv6: 0:0:fe80::42:c0ff MAC: 02:42:c0:a8:2a:02
(更多参考:Linux 获取本机IP、MAC地址用法大全)
windows下,详情见:http://www.cnblogs.com/lzpong/p/6137652.html
--- auth:lzpong