get public IP: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 (n); 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;}
Get intranet IP:int Getlocalip (char* outip) {#ifndef win32int i=0;int sockfd;struct ifconf ifconf;char buf[512];struct ifreq *ifreq;char* ip;//initialization 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); Get all interface information close (SOCKFD);//The next one gets the IP address ifreq = (struct ifreq*) buf;for (i= (ifconf.ifc_len/sizeof (struct ifreq)); >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 next {ifreq++;continue;}} strcpy (OUTIP,IP); return 0; #elsereturn 0; #endif}
C + + Access to public IP address and intranet IP