portCheck.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "publicFunExport.h"
  2. #include <stdio.h>
  3. #include <string>
  4. #if (defined _WIN32 || defined _WIN64)
  5. #include <winsock.h>
  6. #pragma comment(lib,"Ws2_32.lib")
  7. #include "Wininet.h"
  8. #pragma comment(lib,"Wininet.lib")
  9. #else
  10. #include <requests/Exception.hpp>
  11. #include <requests/Request.hpp>
  12. #include <requests/Url.hpp>
  13. #endif
  14. #if (defined _WIN32 || defined _WIN64)
  15. bool checkHttpActive(const char* httpUrl)
  16. {
  17. TCHAR szHostName[128];
  18. TCHAR szUrlPath[256];
  19. URL_COMPONENTS crackedURL = { 0 };
  20. crackedURL.dwStructSize = sizeof(URL_COMPONENTS);
  21. crackedURL.lpszHostName = szHostName;
  22. crackedURL.dwHostNameLength = ARRAYSIZE(szHostName);
  23. crackedURL.lpszUrlPath = szUrlPath;
  24. crackedURL.dwUrlPathLength = ARRAYSIZE(szUrlPath);
  25. InternetCrackUrl(httpUrl, (DWORD)strlen(httpUrl), 0, &crackedURL);
  26. HINTERNET hInternet = InternetOpen("Microsoft InternetExplorer", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
  27. if (hInternet == NULL)
  28. return false;
  29. HINTERNET hHttpSession = InternetConnect(hInternet, crackedURL.lpszHostName, crackedURL.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
  30. if (hHttpSession == NULL)
  31. {
  32. InternetCloseHandle(hInternet);
  33. return false;
  34. }
  35. HINTERNET hHttpRequest = HttpOpenRequest(hHttpSession, "GET", crackedURL.lpszUrlPath, NULL, "", NULL, 0, 0);
  36. if (hHttpRequest == NULL)
  37. {
  38. InternetCloseHandle(hHttpSession);
  39. InternetCloseHandle(hInternet);
  40. return false;
  41. }
  42. /**
  43. * 查询http状态码(这一步不是必须的),但是HttpSendRequest()必须要调用
  44. */
  45. DWORD dwRetCode = 0;
  46. DWORD dwSizeOfRq = sizeof(DWORD);
  47. if (!HttpSendRequest(hHttpRequest, NULL, 0, NULL, 0) ||
  48. !HttpQueryInfo(hHttpRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwRetCode, &dwSizeOfRq, NULL)
  49. || dwRetCode >= 400)
  50. {
  51. InternetCloseHandle(hHttpRequest);
  52. InternetCloseHandle(hHttpSession);
  53. InternetCloseHandle(hInternet);
  54. return false;
  55. }
  56. InternetCloseHandle(hHttpRequest);
  57. InternetCloseHandle(hHttpSession);
  58. return true;
  59. }
  60. #else
  61. bool checkHttpActive(const char* httpUrl)
  62. {
  63. requests::Request request;
  64. requests::Url url(httpUrl);
  65. try
  66. {
  67. // 发起 HTTP 请求,阻塞
  68. auto resp = request.get(url);
  69. return true;
  70. }
  71. catch (requests::Exception& e)
  72. {
  73. std::cout << e.what() << std::endl;
  74. }
  75. return false;
  76. }
  77. #endif