vc 获取外网ip

int GetWan(char *ww)   

{

WSAData wsaDat; 

short int Port = 80; 

WSAStartup(MAKEWORD(1,1),&wsaDat); 

SOCKET sd = socket(AF_INET, SOCK_STREAM, 0);

SOCKADDR_IN sockAddr; 

memset((void*)&sockAddr,0,sizeof(sockAddr)); 

sockAddr.sin_family=AF_INET;

sockAddr.sin_port=htons(Port); 

sockAddr.sin_addr.s_addr=inet_addr("219.153.15.76");

connect(sd, 

   (LPSOCKADDR)&sockAddr, 

   sizeof(sockAddr)); 

char sendstr[]="GET /ip2city.asp HTTP/1.1\r\nAccept: */*\r\nReferer: ******\r\nUser-Agent: Mozilla/4.0\r\nHost: www.ip138.com\r\nConnection: close\r\n\r\n\0"; 

char* p; 

int iLen = strlen(sendstr); 

p = sendstr; 

while (iLen)

{ 

   int iRet = send(sd,p,iLen,0); 

   if (iRet > 0) 

   { 

    p += iRet; 

    iLen -= iRet; 

    continue; 

   } 

   return 0; 

} 

char recvstr[1024]; 

memset(recvstr,0,1024); 

p = recvstr; 

char* iIndex_Head ; 

iLen = 1024; 

int need_len = -1; 

while (iLen)

{ 

   int iRet = recv(sd,p,iLen,0); 

   if (iRet <= 0) 

   { 

    return 0; 

   } 

   p += iRet; 

   iLen -= iRet; 

   if ((iIndex_Head = strstr(recvstr,"\r\n\r\n"))&&(need_len==-1)) 

   { 

    char* iIndex = strstr(recvstr,"Content-Length:"); 

    if (!iIndex) 

    { 

     continue; 

    } 

    char *p1 = iIndex + strlen("Content-Length:"); 

    need_len = iIndex_Head - recvstr + 2 + atol(p1); 

   

   } 

   if (1024 - iLen >=need_len) { break; 

  

   } 

} 

char *p1 = strstr(iIndex_Head,"["); 

char *p0 = strstr(p1,"]"); 

*p0 = '\0';

strcpy(ww,p1+1);

closesocket(sd); 

WSACleanup();

return atoi(ww);

}


你可能感兴趣的:(IP)