CTool.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "stdafx.h"
  2. #include "CTool.h"
  3. #include <WinSock.h>
  4. #include <tcpmib.h>
  5. #include <IPHlpApi.h>
  6. #pragma comment(lib, "IPHlpApi.lib")
  7. #pragma comment(lib, "WS2_32.lib")
  8. CTool* SSingleton<CTool>::ms_Singleton = NULL;
  9. CTool::CTool()
  10. {
  11. WSADATA wsaData;
  12. WSAStartup(0x0201, &wsaData);
  13. }
  14. CTool::~CTool()
  15. {
  16. WSACleanup();
  17. }
  18. std::vector<uint16_t> CTool::GetAllTcpConnectionsPort()
  19. {
  20. std::vector<uint16_t> ret;
  21. ULONG size = 0;
  22. GetTcpTable(NULL, &size, TRUE);
  23. std::unique_ptr<char[]> buffer(new char[size]);
  24. PMIB_TCPTABLE tcpTable = reinterpret_cast<PMIB_TCPTABLE>(buffer.get());
  25. if (GetTcpTable(tcpTable, &size, FALSE) == NO_ERROR)
  26. for (size_t i = 0; i < tcpTable->dwNumEntries; i++)
  27. ret.push_back(ntohs((uint16_t)tcpTable->table[i].dwLocalPort));
  28. std::sort(std::begin(ret), std::end(ret));
  29. return ret;
  30. }
  31. std::vector<uint16_t> CTool::GetAllUdpConnectionsPort()
  32. {
  33. std::vector<uint16_t> ret;
  34. ULONG size = 0;
  35. GetUdpTable(NULL, &size, TRUE);
  36. std::unique_ptr<char[]> buffer(new char[size]);
  37. PMIB_UDPTABLE udpTable = reinterpret_cast<PMIB_UDPTABLE>(buffer.get());
  38. if (GetUdpTable(udpTable, &size, FALSE) == NO_ERROR)
  39. for (size_t i = 0; i < udpTable->dwNumEntries; i++)
  40. ret.push_back(ntohs((uint16_t)udpTable->table[i].dwLocalPort));
  41. std::sort(std::begin(ret), std::end(ret));
  42. return ret;
  43. }
  44. uint16_t CTool::FindAvailableTcpPort(uint16_t begin, uint16_t end)
  45. {
  46. auto vec = GetAllTcpConnectionsPort();
  47. for (uint16_t port = begin; port != end; ++port)
  48. if (!std::binary_search(std::begin(vec), std::end(vec), port))
  49. return port;
  50. return 0;
  51. }
  52. uint16_t CTool::FindAvailableUdpPort(uint16_t begin, uint16_t end)
  53. {
  54. auto vecTcp = GetAllTcpConnectionsPort(),
  55. vecUdp = GetAllUdpConnectionsPort();
  56. for (uint16_t port = begin; port != end; ++port)
  57. if (!std::binary_search(std::begin(vecTcp), std::end(vecTcp), port) &&
  58. !std::binary_search(std::begin(vecUdp), std::end(vecUdp), port))
  59. return port;
  60. return 0;
  61. }