C/C ++ obtains public ip addresses and Intranet ip addresses.
Obtain the public ip Address:bool getPublicIp(string& ip){ int sock; char **pptr = NULL; struct sockaddr_in destAddr; struct hostent *ptr = NULL; char destIP[128]; sock = socket(AF_INET,SOCK_STREAM,0); if( -1 == sock ){ perror("creat socket failed"); return false; } bzero((void *)&destAddr,sizeof(destAddr)); destAddr.sin_family = AF_INET; destAddr.sin_port = htons(80); ptr = gethostbyname("www.ip138.com"); if(NULL == ptr){ perror("gethostbyname error"); return false; } for(pptr=ptr->h_addr_list ; NULL != *pptr ; ++pptr){ inet_ntop(ptr->h_addrtype,*pptr,destIP,sizeof(destIP)); printf("addr:%s\n",destIP); ip = destIP; return true; } return true;}
Obtain the Intranet ip Address:Int getlocalip (char * outip) {# ifndef WIN32int I = 0; int sockfd; struct ifconf; char buf [512]; struct ifreq * ifreq; char * ip; // initialize ifconfifconf. ifc_len= 512; ifconf. ifc_buf = buf; strcpy (outip, "127.0.0.1"); if (sockfd = socket (AF_INET, SOCK_DGRAM, 0) <0) {return-1;} ioctl (sockfd, SIOCGIFCONF, & ifconf); // obtain all interface information close (sockfd); // obtain the IP address ifreq = (struct ifreq *) buf one by one; for (I = (ifconf. ifc_len/sizeof (struct ifreq); I> 0; I --) {ip = inet_ntoa (struct sockaddr_in *) & (ifreq-> ifr_addr)-> sin_addr ); if (strcmp (ip, "127.0.0.1") = 0) // exclude 127.0.0.1, continue to the next {ifreq ++; continue ;}} strcpy (outip, ip); return 0; # elsereturn 0; # endif}