[cpp]
#include "stdafx.h"
BOOL GetPubIp(char *ip);
int main()
{
char myip[32]={0};
GetPubIp(myip);
cout<<myip<<endl;
return 0;
}
BOOL GetPubIp(char *ip)
{
HINTERNET hInternet=NULL;
HINTERNET hConnect=NULL;
char szText[512]={0};
char *szAccept="Accept: */*\r\n\r\n";
char *szUrl="http://www.ip138.com/ip2city.asp";
DWORD dwReadLen=0;
__try
{
hInternet=InternetOpen("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",0,NULL,NULL,0);
if(!hInternet)
__leave;
hConnect=InternetOpenUrl(hInternet,szUrl,szAccept,strlen(szAccept),INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_PRAGMA_NOCACHE|INTERNET_FLAG_RELOAD,0);
if(!hConnect)
__leave;
InternetReadFile(hConnect,szText,512,&dwReadLen);
}
__finally
{
if(hInternet)
InternetCloseHandle(hInternet);
if(hConnect)
InternetCloseHandle(hConnect);
}
char *start=strstr(szText,"您的IP地址是:[");
if(!start)
return FALSE;
start=start+15;
char *temp=strstr(start,"]");
strncpy(ip,start,temp-start);
return TRUE;
}
摘自 sniper_bing的專欄