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 129 130 131 132
| /*
Concours 12 pour SecurityHack
gcc -o Server concours12.c -lpthread
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(WIN32)
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#endif
#include <pthread.h>
#define PORT 2200
#define BACKLOG 2
#define MAXSIZE 1024
void str_reverse(char * string)
{
int i = 0;
int size = strlen(string);
char cBuffer;
for(i=0;i < size/2 + 1;i++)
{
cBuffer = string[i];
string[i] = string[size-1-i];
string[size-1-i] = cBuffer;
}
}
void * new_client(int sock_accept)
{
char * string = (char *) malloc(MAXSIZE*sizeof(char));
int length;
if(send(sock_accept,"Entrez une phrase : \n",21,0) == -1)
{
perror("send");
}
if((length = recv(sock_accept,string,MAXSIZE,0)) == -1)
perror("recv");
else
{
string[length-1]='\0';
fprintf(stdout,"Chaine recue : %s \n",string);
}
str_reverse(string);
if(send(sock_accept,string,strlen(string)+1,0) == -1)
perror("send");
else
fprintf(stdout,"Chaine renvoye : %s \n",string);
#if defined(WIN32)
closesocket(sock_accept);
#else
close(sock_accept);
#endif
free(string);
pthread_exit(0);
return NULL;
}
int main(int argc, char * argv[])
{
#if defined(WIN32)
WSADATA WSAData;
WSAStartup(MAKEWORD(2,0), &WSAData);
#endif
int sock;
int sock_accept;
struct sockaddr_in server;
struct sockaddr_in client;
int sin_size;
pthread_t thread;
if((sock = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror("socket");
exit(1);
}
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = INADDR_ANY;
memset(&(server.sin_zero),'\0',8);
if(bind(sock,(struct sockaddr * )&server,sizeof(struct sockaddr)) == -1)
{
perror("bind");
exit(1);
}
if(listen(sock,BACKLOG) == -1)
{
perror("listen");
exit(1);
}
fprintf(stdout,"En attente de connection ...\nCTRL + C pour quitter!\n");
while(1)
{
sin_size = sizeof(struct sockaddr_in);
if((sock_accept = accept(sock,(struct sockaddr * )&client,&sin_size)) == -1)
perror("accept");
else
{
fprintf(stdout,"Connection de : %s \n",inet_ntoa(client.sin_addr));
pthread_create(&thread,NULL,new_client,sock_accept);
}
}
return 0;
} |
Partager