1 #include<wininet.h>
2 #pragma comment(lib,"wininet.lib")
3
4 DWORD HttpGet(LPCTSTR, char *, int);
5 void GetPublicIp(char *pIP, int len)
6 {
7 char szBuffer[1024];
8 memset(szBuffer, 0, sizeof(char) * 1024);
9 if (HttpGet(_TEXT("http://city.ip138.com/ip2city.asp"), szBuffer, 1024))
10 {
11 char* begin = strstr(szBuffer, "[");
12 char* end = strstr(begin, "]");
13 if (begin == NULL || end == NULL)
14 return;
15 int offset = end - begin - 1;
16 begin[offset] = '\0';
17 char *ip = begin;
18
19 strncpy_s(pIP, len, ip, offset);
20 }
21 }
22
23 DWORD HttpGet(LPCTSTR lpszFullUrl, char *pBuffer, int iBufferSize)
24 {
25 if (lpszFullUrl == NULL)
26 return 0;
27
28 HINTERNET hNet = ::InternetOpen(_TEXT("Mozilla/5.0 (Windows NT 6.3; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0"),
29 PRE_CONFIG_INTERNET_ACCESS,
30 NULL,
31 INTERNET_INVALID_PORT_NUMBER,
32 0);
33 if (hNet == NULL)
34 {
35 return 0;
36 }
37
38 HINTERNET hUrlFile = ::InternetOpenUrl(hNet,
39 lpszFullUrl,
40 NULL,
41 0,
42 INTERNET_FLAG_RELOAD,
43 0);
44
45 if (!hUrlFile)
46 {
47 return 0;
48 }
49
50 ::memset(pBuffer, 0, iBufferSize);
51 DWORD dwBytesRead = 0;
52 char szTemp[1024] = { 0 };
53 DWORD dwTotalReadBytes = 0;
54 while (InternetReadFile(hUrlFile, szTemp, sizeof(szTemp) - 1, &dwBytesRead))
55 {
56 if (0 == dwBytesRead)
57 break;
58 szTemp[dwBytesRead] = 0;
59
60 // 缓冲区大小不够时,停止向目的缓冲区复制数据,跳出
61 if (dwTotalReadBytes + dwBytesRead >= (UINT)iBufferSize)
62 {
63 pBuffer[iBufferSize - 1] = 0;
64 break;
65 }
66
67 strcat_s(pBuffer, 1024, szTemp);
68 ZeroMemory(szTemp, sizeof(szTemp));
69
70 dwTotalReadBytes += dwBytesRead;
71
72 }
73
74 ::InternetCloseHandle(hUrlFile);
75 ::InternetCloseHandle(hNet);
76 return dwTotalReadBytes;
77 }
78
79