Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdio.h>
- #include <winsock2.h>
- #include <ws2tcpip.h>
- #include <process.h> /* _beginthread() */
- #include <new>
- unsigned __stdcall thread_test(void *)
- {
- _endthreadex(0);
- return 0;
- }
- int main()
- {
- WORD wVersion = MAKEWORD(2, 2);
- WSADATA wsaData;
- int iResult;
- SOCKET sock;
- struct addrinfo hints, *res;
- int reuseaddr = 1; /* True */
- /* Initialise Winsock */
- if ((iResult = WSAStartup(wVersion, &wsaData)) != 0) {
- printf("WSAStartup failed: %d\n", iResult);
- return 1;
- }
- /* Get the address info */
- ZeroMemory(&hints, sizeof hints);
- hints.ai_family = AF_INET;
- hints.ai_socktype = SOCK_STREAM;
- if (getaddrinfo("0.0.0.0", "80", &hints, &res) != 0) {
- perror("getaddrinfo");
- return 1;
- }
- /* Create the socket */
- sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
- if (sock == INVALID_SOCKET) {
- perror("socket");
- WSACleanup();
- return 1;
- }
- /* Enable the socket to reuse the address */
- if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuseaddr,
- sizeof(int)) == SOCKET_ERROR) {
- perror("setsockopt");
- WSACleanup();
- return 1;
- }
- /* Bind to the address */
- if (bind(sock, res->ai_addr, res->ai_addrlen) == SOCKET_ERROR) {
- perror("bind");
- WSACleanup();
- return 1;
- }
- freeaddrinfo(res);
- /* Listen */
- if (listen(sock, 10) == SOCKET_ERROR) {
- perror("listen");
- WSACleanup();
- return 1;
- }
- /* Main loop */
- while (1) {
- int size = sizeof(struct sockaddr);
- struct sockaddr_in their_addr;
- int newsock;
- ZeroMemory(&their_addr, sizeof (struct sockaddr));
- newsock = accept(sock, (struct sockaddr*)&their_addr, &size);
- if (newsock == INVALID_SOCKET) {
- perror("INVALID_SOCKET\n");
- }
- else {
- /* Use the new socket */
- closesocket(newsock);
- //if i comment these two lines below, it gives no more leaks
- HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, thread_test, NULL, 0, NULL);
- CloseHandle(hThread);
- }
- }
- /* Clean up */
- closesocket(sock);
- WSACleanup();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement