1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
|
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <winsock.h>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// simple telnet server that can receive commands and messages from multiple clients
DWORD WINAPI receive_cmds(LPVOID lpParam)
{
char buf[256] = " ";
char sendData[256];
int res;
string test;
printf(">A client has connected\n");
SOCKET current_client = (SOCKET)lpParam;
Beep(523,500);
strcpy(sendData,"(0 to QUIT)\n\rcasey.provost@eagles.usm.edu\n\n\r");
send(current_client,sendData,45,0);
while(true)
{
res = recv(current_client,buf,sizeof(buf[100]),0);
Sleep(10);
if(res == 0)
{
closesocket(current_client);
ExitThread(0);
}
if(buf != "0"){ // 0 to exit
printf(buf);
}
if(strstr(buf,"0"))
{
printf("\n>Received exit command\n");
strcpy(sendData,"Good Bye\n");
send(current_client,sendData,8,0);
Sleep(1000);
closesocket(current_client);
printf(">A client has disconnected\n");
Beep(659,500);
ExitThread(0);
}
strcpy(sendData,"");
strcpy(buf,"");
}
}
int main()
{
printf(">Server starting...\r\n");
SOCKET sock;
printf(">Socket created...\r\n");
DWORD thread;
WSADATA wsaData;
sockaddr_in server;
int ret = WSAStartup(0x101,&wsaData);
printf(">Winsock started...\r\n");
if(ret != 0)
{
return 0;
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(23);
sock=socket(AF_INET,SOCK_STREAM,0);
if(sock == INVALID_SOCKET)
{
return 0;
}
if( bind(sock,(sockaddr*)&server,sizeof(server)) !=0 )
{
return 0;
}
printf(">Server is online\r\n");
if(listen(sock,5) != 0)
{
return 0;
}
SOCKET client; // socket to be used
sockaddr_in from;
int fromlen = sizeof(from);
while(true) // loop forever
{
client = accept(sock,(struct sockaddr*)&from,&fromlen);
// accept connections
CreateThread(NULL, 0,receive_cmds,(LPVOID)client, 0, &thread);
// create thread and parse client
}
closesocket(sock);
WSACleanup();
printf(">Socket closed\r\n");
return 0;
// exit
}
|