C/C ++ obtains public ip addresses and Intranet ip addresses.

Source: Internet
Author: User

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}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.