window winhttp
#include <iostream> #include <algorithm> #include <string> #include <cstdlib> #include <windows.h> #include <winhttp.h> #include <regex> #pragma comment(lib, "winhttp.lib") using namespace std; int main(int argc, char* argv[]) { DWORD dwSize = 0; DWORD dwDownloaded = 0; LPSTR pszOutBuffer; BOOL bResults = FALSE; HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; //1. 初始化一个WinHTTP-session句柄,参数1为此句柄的名称 hSession = WinHttpOpen(L"GetIP", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); // 通过上述句柄连接到服务器 需要指定服务器的IP和端口号,如果连接成功 返回的hConnect句柄不为NULL if (hSession) hConnect = WinHttpConnect(hSession, L"myip.ipip.net", INTERNET_DEFAULT_HTTP_PORT, 0); //默认是80 // 通过hConnect句柄创建一个hRequest句柄,用于发送数据与读取从服务器返回的数据。 // 参数2表示请求方式 这边我是用get 如果是post 要给出具体的地址 if (hConnect) hRequest = WinHttpOpenRequest(hConnect, L"GET", L"", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); // 向服务器发送post数据 if (hRequest) bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); // Continue to verify data until there is nothing left. if (bResults) { do { // Verify available data. dwSize = 0; if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) printf("Error %u in WinHttpQueryDataAvailable.\n", GetLastError()); if (dwSize == 0) break; // Allocate space for the buffer. pszOutBuffer = new char[dwSize + 1]; // Read the Data. ZeroMemory(pszOutBuffer, dwSize + 1); if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) printf("Error %u in WinHttpReadData.\n", GetLastError()); else { printf("%s\n", pszOutBuffer); char* pszBuffer = new char[dwSize + 1]; wchar_t* pszWideBuffer = new wchar_t[(dwSize + 1) * 2]; memset(pszWideBuffer, 0, (dwSize + 1) * 2); memset(pszBuffer, 0, dwSize + 1); MultiByteToWideChar(CP_UTF8, 0, pszOutBuffer, dwSize, pszWideBuffer, (dwSize + 1) * 2); //将unicode编码,转换为宽字节 WideCharToMultiByte(CP_ACP, 0, pszWideBuffer, wcslen(pszWideBuffer), pszBuffer, dwSize + 1, NULL, NULL); //将宽字节,转换为控制台编码 printf("%s\n", pszBuffer); string info(pszBuffer); delete[] pszBuffer; delete[] pszWideBuffer; std::smatch result; std::regex pattern( "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); //正则表达式 std::string::const_iterator iterStart = info.begin(); std::string::const_iterator iterEnd = info.end(); std::string temp = ""; if (regex_search(iterStart, iterEnd, result, pattern)) { temp = result[0]; } printf("%s", temp.c_str()); } // Free the memory allocated to the buffer. delete[] pszOutBuffer; } while (dwSize > 0); } // Report errors. if (!bResults) printf("Error %d has occurred.\n", GetLastError()); // Close open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); }