Advertisement
Guest User

Untitled

a guest
May 18th, 2014
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <winsock2.h>
  4. #include <ws2tcpip.h>
  5. #include <process.h> /* _beginthread() */
  6. #include <new>
  7.  
  8.  
  9. unsigned __stdcall thread_test(void *)
  10. {
  11. _endthreadex(0);
  12. return 0;
  13. }
  14.  
  15. int main()
  16. {
  17. WORD wVersion = MAKEWORD(2, 2);
  18. WSADATA wsaData;
  19. int iResult;
  20. SOCKET sock;
  21. struct addrinfo hints, *res;
  22. int reuseaddr = 1; /* True */
  23.  
  24. /* Initialise Winsock */
  25. if ((iResult = WSAStartup(wVersion, &wsaData)) != 0) {
  26. printf("WSAStartup failed: %d\n", iResult);
  27. return 1;
  28. }
  29.  
  30.  
  31. /* Get the address info */
  32. ZeroMemory(&hints, sizeof hints);
  33. hints.ai_family = AF_INET;
  34. hints.ai_socktype = SOCK_STREAM;
  35. if (getaddrinfo("0.0.0.0", "80", &hints, &res) != 0) {
  36. perror("getaddrinfo");
  37. return 1;
  38. }
  39.  
  40. /* Create the socket */
  41. sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  42. if (sock == INVALID_SOCKET) {
  43. perror("socket");
  44. WSACleanup();
  45. return 1;
  46. }
  47.  
  48. /* Enable the socket to reuse the address */
  49. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuseaddr,
  50. sizeof(int)) == SOCKET_ERROR) {
  51. perror("setsockopt");
  52. WSACleanup();
  53. return 1;
  54. }
  55.  
  56. /* Bind to the address */
  57. if (bind(sock, res->ai_addr, res->ai_addrlen) == SOCKET_ERROR) {
  58. perror("bind");
  59. WSACleanup();
  60. return 1;
  61. }
  62.  
  63. freeaddrinfo(res);
  64.  
  65. /* Listen */
  66. if (listen(sock, 10) == SOCKET_ERROR) {
  67. perror("listen");
  68. WSACleanup();
  69. return 1;
  70. }
  71.  
  72. /* Main loop */
  73. while (1) {
  74. int size = sizeof(struct sockaddr);
  75. struct sockaddr_in their_addr;
  76. int newsock;
  77.  
  78. ZeroMemory(&their_addr, sizeof (struct sockaddr));
  79. newsock = accept(sock, (struct sockaddr*)&their_addr, &size);
  80. if (newsock == INVALID_SOCKET) {
  81. perror("INVALID_SOCKET\n");
  82. }
  83. else {
  84. /* Use the new socket */
  85. closesocket(newsock);
  86.  
  87. //if i comment these two lines below, it gives no more leaks
  88. HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, thread_test, NULL, 0, NULL);
  89. CloseHandle(hThread);
  90. }
  91. }
  92.  
  93. /* Clean up */
  94. closesocket(sock);
  95. WSACleanup();
  96.  
  97. return 0;
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement