C + + Access to public IP address and intranet IP

Source: Internet
Author: User

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

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.