| 12
 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
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 
 | /********************************************************************
*   Serveur simple portable (Socket en langage C)
*             Compilé avec GCC (sous Code::Blocks)
*
*        Programed by Bug_Bug: one_piece_555(AT)hotmail.fr
*
*   P.S. N'oubliez pas de linker avec la blibiothèque -lws2_32
*          voir libwsock32.a ou libws2_32.a ou ws2_32.lib ...
*********************************************************************/
 
/**==================[ Si Windows ]================**/
#if defined (WIN32)  /* Si on compile ce code source sous Windows, alors: */
#include <winsock2.h>
 
/**================[ Si Gnu/Linux ]================**/
#elif defined (linux) /* Sinon si on compile sous linux, alors: */
 
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
 
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
 
#define closesocket(s) close (s)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
 
/**===============[ Si Autre Systems ]==============**/
#else
#error not defined for this platform
#endif /**========[ Fin teste portabilite' ]========**/
 
/* Inclure les fichiers d'en-tete dont on a besoin */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define DEBUG 0 /** Aclive: 1,  Desactive: 0 **/
#define SERVER_PORT_LISTENING 3113
 
int App (void);
int ConnectWithClient ( SOCKET*, SOCKET* );
int CommunicatWithClient ( SOCKET );
int RecvData ( SOCKET socket, char *data );
 
char buffer[65535];
 
/**************************************************************************
* Fonction main():
* La fonction principale ( le point d'entrer )...
***************************************************************************/
int main (void)
{
   int flag_main_exit = EXIT_SUCCESS;
 
/**==================[ Si Windows ]================**/
#if defined (WIN32)
   WSADATA wsa_data;
   /* Si l'initialisation sous windows echoue */
   if ( WSAStartup (MAKEWORD (2, 2), &wsa_data) )
      return EXIT_FAILURE;
 
   puts ("Windows: winsock2: OK");
#endif /**===========[ Fin teste Windows ]==========**/
 
 
   /* si app() retourne 1 c'est qu'elle a echoue' */
   if ( App () )
      flag_main_exit = EXIT_FAILURE;
 
 
/**==================[ Si Windows ]================**/
#if defined (WIN32)
   /* Fermer ce qu'on a initialiser avec WSAStartup */
   WSACleanup ();
#endif /**===========[ Fin teste Windows ]==========**/
 
   puts("\nPress any key to exit this program ...");
   getchar();
   return flag_main_exit;
}
 
 
/**************************************************************************
* Fonction App():
** Le Serveur se connecte avec le client: ConnectToServer()
** Si connexion etablie, passer a' la communication CommunicatWithClient()
***************************************************************************/
int App (void)
{
   SOCKET sock, csock;
   int sock_err;
 
    if( ConnectWithClient (&csock, &sock) )
      return 1; /* retourne 1 s'il y eu probleme */
 
   if ( CommunicatWithClient(csock) )
      return 1; /* retourne 1 s'il y eu probleme */
 
   /* Fin de communication, fermer socket proprement */
   shutdown (sock, 2);   shutdown (csock, 2);
   sock_err = closesocket (sock), sock = INVALID_SOCKET;
   if (sock_err == SOCKET_ERROR)
   {
      perror("Error: sock.closesocket()");
      return 1;
   }
 
   return 0;
}
 
 
 
/******************************************************************************
* Fonction: ConnectWithClient()
** Connexion avec le client (avec sock), et recuperation d'infos
**        sur le client, sur csock ...
******************************************************************************/
int ConnectWithClient ( SOCKET *csock, SOCKET *sock )
{
   /* Declaration de 2 structures de type SOCKADDR_IN */
   SOCKADDR_IN sin; /* pour le serveur */
   SOCKADDR_IN csin; /* pour le client */
 
   int sock_err, recsize;
 
   FILE* fichier = fopen("log.txt", "a");
 
   /* ouverture du socket */
   if ( (*sock = socket (AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
   {
      perror("socket.open");
      return 1; /* Creation du socket a echouer */
   }
 
   printf ("socket %d est maintenant ouvert en mode TCP/IP\n", *sock);
 
   sin.sin_addr.s_addr = htonl (INADDR_ANY); /* Pas besoin d'IP */
   sin.sin_port = htons (SERVER_PORT_LISTENING);  /* port d'ecoute */
   sin.sin_family = AF_INET;  /* famille du protocol (IP) */
 
   /* bind du socket serveur (sock) avec la structure sin du serveur */
   sock_err = bind (*sock, (SOCKADDR *) &sin, sizeof sin);
   if (sock_err == SOCKET_ERROR)
   {
      perror("Error: bind");
      return 1;
   }
 
   /* ecoute sur le port */
   if ( (sock_err = listen (*sock, 5)) == SOCKET_ERROR)
   {
      perror("Error: listen");
      return 1;
   }
   printf ("ecoute sur le port %d...\n", SERVER_PORT_LISTENING);
 
   /* attendre et accepter la connection du client en recuperant les infos
      sur le client dans csin, et en créant le socket du client csock */
   recsize = (int) sizeof csin;
   if( (*csock = accept(*sock, (SOCKADDR*) &csin, &recsize)) == INVALID_SOCKET)
   {
      perror("Error: accept");
      return 1;
   }
   printf ("client connecte avec socket: %d    de: %s   port: %d\n",
               *csock,    inet_ntoa (csin.sin_addr)    ,htons (csin.sin_port));
 
   if(fichier != NULL)
   {
      fputs("-----------------------------------\n", fichier);
      fprintf(fichier, "client connecte avec socket: %d    de: %s   port: %d\n",
               *csock,    inet_ntoa (csin.sin_addr)    ,htons (csin.sin_port));
      fputs("-----------------------------------\n", fichier);
 
      fclose(fichier);
   }
 
   return 0;
}
 
 
 
/******************************************************************************
* Fonction: CommunicatWithClient()
** Premet d'echanger des donnees avec le Client.   Recevoir ou Envoyer
******************************************************************************/
int CommunicatWithClient ( SOCKET csock )
{
   char data[500 + 1];
   int sock_err, err_close;
   FILE* fichier = fopen("log.txt", "a");
 
   do
   {
      /* Attendre et recevoire des données envoyé par le client */
      if ( (sock_err = RecvData (csock, data)) == SOCKET_ERROR )
         break;
 
      else
      {
         data[sock_err] = '\0';
 
         printf("> %s\n", data);
 
 
         if(fichier != NULL)
            fprintf(fichier, "> %s\n", data);
      }
   }
   while (1);
 
   if(fichier != NULL)
      fclose(fichier);
 
   /* fermeture du socket client (csock), fin de la communication */
   shutdown (csock, 2);
   err_close = closesocket (csock), csock = INVALID_SOCKET;
   if (err_close == SOCKET_ERROR)
   {
      perror("Error: csock.closesocket()");
      return 1;
   }
 
   return 0;
}
 
 
 
 
/******************************************************************************
* Fonction: RecvData()
** Permet de recevoir proprement un Bloc de données
** Retourne la taille de data reçu
******************************************************************************/
int RecvData ( SOCKET sock, char *data )
{
   size_t len_data;
   size_t data_receved = 0;
   char textmode_lendata[25], *pend;
   int n;
 
   /* Recevoir la taille de data */
   n = recv(sock, textmode_lendata, sizeof textmode_lendata - 1, 0);
 
   if (n <= 0)
   {
      if( n == 0 )
         printf("Le Client 'a Quitter...\n");
      return SOCKET_ERROR;
   }
   else
   {
      textmode_lendata[n] = '\0';
      len_data = strtol (textmode_lendata, &pend, 10);
      if (*pend != '\n')
      {
         printf("Invalid data size receved !\n");
         return -1;
      }
   }
 
   /* TantQu'on as pas recu tout, on continue ... */
   while (data_receved < len_data)
   {
      n = recv (sock, data + data_receved, sizeof data - 1, 0);
 
      if (n > 0)
         data_receved += n;
      else
         return SOCKET_ERROR;
   }
 
   return ((int)data_receved);
} |