通过www.ip138.com获取本机外网ip以及所在地理位置

INT ip138_getinfo(LPSTR lpszIP, LPSTR lpszAddress)
{
//GET /ic.asp HTTP/1.1..
//Accept: */*..
//Referer: http://www.ip138.com/..
//Accept-Language: zh-cn..
//Accept-Encoding: gzip, deflate..
//User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; qihu theworld)..
//Host: iframe.ip138.com..
//Connection: Keep-Alive..
//Cookie: ASPSESSIONIDQASSDTAT=MAPFLNODFDJFDKHIMAKNMOEF; ASPSESSIONIDQCQTDTAT=AOADLNODBDEIAJLHMNHHIIFD; ASPSESSIONIDSCTTCSAS=FDJBLNODEGMLIJFJIBMKNCHP; ASPSESSIONIDQAQQBRCT=PKEELNODGBNOFKDEPIBIDEJM....
//
//HTTP/1.1 200 OK..
//Date: Wed, 11 Sep 2013 09:26:06 GMT..
//Server: Microsoft-IIS/6.0..
//X-Powered-By: ASP.NET..
//Content-Length: 228..
//Content-Type: text/html..
//Set-Cookie: ASPSESSIONIDSCRTCSBT=LDPOKNODEEGJLABMGGKCMNAJ; path=/..
//Cache-control: private....
//
//..
//..
//..
// ....IP.... ....
....IP....[218.88.92.53] .................. ....
int ret = 1; CInternetSession Session; CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; CString strHeader = "Accept: */*\r\n"; strHeader.Append("Referer: http://www.ip138.com/\r\n"); strHeader.Append("Accept-Language: zh-cn\r\n"); strHeader.Append("Accept-Encoding: gzip, deflate\r\n"); strHeader.Append("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)\r\n"); CString strUrl; strUrl.Format("/ic.asp"); pServer = Session.GetHttpConnection("iframe.ip138.com"); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,strUrl, NULL, 1, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_COOKIES); pFile->AddRequestHeaders(strHeader); try{ pFile->SendRequest(); } catch(...){ ret = -1; } CString strInfo; CString str; BYTE buffer[0x500] = { 0 }; char info[0x500] = { 0 }; int n = pFile->Read(buffer, 0x500); pFile->Close(); delete pFile; strInfo = (LPCSTR)buffer; int i = strInfo.Find("["); if(i == -1) return 0; strInfo = strInfo.Right(strInfo.GetLength() - i - strlen("[")); i = strInfo.Find("]"); if(i == -1) return 0; str = strInfo.Left(i); strcpy_s(lpszIP, str.GetLength()+1, str); strInfo = strInfo.Right(strInfo.GetLength() - i - strlen("]")); i = strInfo.Find(":"); if(i == -1) return 0; strInfo = strInfo.Right(strInfo.GetLength() - i - strlen(":")); i = strInfo.Find("<"); if(i == -1) return 0; str = strInfo.Left(i); strcpy_s(lpszAddress, str.GetLength()+1, str); return ret; }


调用方式:

HMODULE hWebHelper = ::LoadLibrary("WebHelper.dll");

typedef DWORD (*_GetLocalHost) (LPSTR lpszIP, LPSTR lpszAddress);
_GetLocalHost GetLocalHost;

GetLocalHost = (_GetLocalHost)GetProcAddress(hWebHelper, "GetLocalHost");

char ip[0x20] = { 0 };
char addr[0x100] = { 0 };
int ret = GetLocalHost(ip, addr);

你可能感兴趣的:(C++)