Gonzalez Posted September 7, 2009 Report Posted September 7, 2009 /* * Multi-Threaded Server* by; android @ blackhacking.com*/#include <stdio.h>#include <Winsock2.h>#include <Ws2tcpip.h>#include <cstdlib>void ListenThread(LPVOID listenParams);int CommunicateThread(LPVOID params);typedef struct { int ListenSocket;} ListenParameters;typedef struct { struct sockaddr_in client; int socket;} ConnectedSocket;int main(int argc, char *argv[]) { WSADATA wsaData; int servSocket; struct sockaddr_in serv; ListenParameters listenParams; char buf[1024] = {0}; unsigned short port = atoi(argv[1]); if (argc != 1 || !port) { printf("Usage: <server.exe> <port>\n"); return 0; } if (WSAStartup(MAKEWORD(2,2), &wsaData)) { printf("WSAStartup failed!"); return 1; } serv.sin_family = AF_INET; serv.sin_addr.S_un.S_addr = NULL; serv.sin_port = htons(port); servSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); bind(servSocket, (sockaddr *)&serv, sizeof(serv)); listenParams.ListenSocket = servSocket; CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&ListenThread, &listenParams, 0, 0); while (true) Sleep(5000); closesocket(servSocket); WSACleanup(); return 0;}void ListenThread(LPVOID params) { ListenParameters listenParams = *(ListenParameters *)params; struct sockaddr_in client; int tempSock; socklen_t clientSize; clientSize = sizeof(client); listen(listenParams.ListenSocket, SOMAXCONN); while (true) { tempSock = accept(listenParams.ListenSocket, (sockaddr *)&client, &clientSize); if (tempSock == SOCKET_ERROR) continue; printf("%s:%d // Connection Initiated\n", inet_ntoa(client.sin_addr), client.sin_port); ConnectedSocket socketStruct; socketStruct.client = client; socketStruct.socket = tempSock; CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&CommunicateThread, &socketStruct, 0, 0); Sleep(50); } ExitThread(0);}int CommunicateThread(LPVOID params) { ConnectedSocket connectedSocket = *(ConnectedSocket *)params; int socket = connectedSocket.socket; char * addr = inet_ntoa(connectedSocket.client.sin_addr); short port = connectedSocket.client.sin_port; char * reply = "Reply from server!\n"; send(socket, reply, strlen(reply), 0); printf("%s:%d // Sent: %s\n", addr, port, reply); printf("%s:%d // Connection Terminated", addr, port); closesocket(socket); ExitThread(0);} Quote