Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

COMMUNICATION CLIENT SERVEUR , TRANSMITION DE DONNÉES PAR TRAMES , SOCKETS EN LANGAGE C


Information sur la source

Catégorie :Réseaux & Internet Classé sous : sockets, client, serveur, trames, portable Niveau : Initié Date de création : 09/09/2007 Date de mise à jour : 11/09/2007 11:29:16 Vu / téléchargé: 12 113 / 2 714

Note :
10 / 10 - par 4 personnes
10,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

Commentaire sur cette source (14)
Ajouter un commentaire et/ou une note

Description

Ceci est le code source portable d'un Client Serveur simple en langage C.
Ce code source permet tout simplement d'envoyer des chaines de caractère en du client au serveur;
Le client envoi ces donnée par petit blocs (Trames) en mode texte, Et le serveur reçois la taille de données, puis reçois et reconstitue le texte à partir des Trames reçu.


 

Source

  • /* Vous pouvez aussi télécharger le ZIP qui contiens les sources */
  • /********************************************************************
  • * Client 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 ...
  • *********************************************************************/
  • /* Verifier que le compilateur est bien un compilateur C et pas C++ */
  • #ifdef __cplusplus
  • #error Be sure you are using a C compiler...
  • #endif
  • /**==================[ Si Windows ]================**/
  • #if defined (WIN32)
  • #include <winsock2.h>
  • /**================[ Si Gnu/Linux ]================**/
  • #elif defined (linux)
  • #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>
  • #define SERVER_PORT_CONNEXION 3113
  • char ip_server[15] = "127.0.0.1"; /* localhost */
  • int App (void);
  • int ConnectToServer (SOCKET*);
  • int CommunicatWithServer (SOCKET);
  • int SendData (SOCKET, char*);
  • /**************************************************************************
  • * Fonction main():
  • * La fonction principale ( le point d'entrer )...
  • ***************************************************************************/
  • int main (void)
  • {
  • int flag_main_exit = EXIT_SUCCESS;
  • /**==================[ Si Windows ]================**/
  • #if defined (WIN32)
  • /* Initialiser WSAStartup() */
  • WSADATA wsa_data;
  • if ( WSAStartup (MAKEWORD (2, 2), &wsa_data) )
  • {
  • perror("Error: init WSAStartup()");
  • return EXIT_FAILURE;
  • }
  • puts ("WIN: winsock2: OK");
  • #endif /**===========[ Fin teste Windows ]==========**/
  • /* si app() retourne 1 c'est qu'elle a echoué */
  • 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 Client se connecte au serveur: ConnectToServer()
  • ** Si connexion etablie, passer a' la communication CommunicatWithServer()
  • ***************************************************************************/
  • int App (void)
  • {
  • SOCKET fdsock;
  • int sock_err;
  • if ( ConnectToServer (&fdsock) )
  • return 1; /* retourne 1 s'il y eu probleme */
  • if ( CommunicatWithServer(fdsock) )
  • return 1; /* retourne 1 s'il y eu probleme */
  • /* Fin de communication, fermer socket proprement */
  • shutdown (fdsock, 2);
  • sock_err = closesocket (fdsock), fdsock = INVALID_SOCKET;
  • if (sock_err == SOCKET_ERROR)
  • {
  • perror("Error: closesocket()");
  • return 1;
  • }
  • return 0; /* Success */
  • }
  • /******************************************************************************
  • * Fonction: ConnectToServer()
  • ** Connexion avec le serveur (ip_server) sur le port SERVER_PORT_CONNEXION
  • ******************************************************************************/
  • int ConnectToServer ( SOCKET* fdSock )
  • {
  • /* Declaration d'une structure sin de type SOCKADDR_IN
  • Qui contiendra les infos consernant le serveur, (IP, port, type) */
  • SOCKADDR_IN sin;
  • /* Creation du socket: */
  • if ( (*fdSock = 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", *fdSock);
  • /* l'IP du serveur avec lequel on va ce connecter: */
  • sin.sin_addr.s_addr = inet_addr(ip_server);
  • /* le port avec lequel on va ce connecter sur le serveur: */
  • sin.sin_port = htons (SERVER_PORT_CONNEXION);
  • /* famille du protocol (IP): */
  • sin.sin_family = AF_INET;
  • if ( connect(*fdSock, (SOCKADDR *)&sin, sizeof sin) == SOCKET_ERROR )
  • {
  • perror("Error: connect");
  • return 1;
  • }
  • printf ( "Vous etes maintenant connecter au serveur %s sur le port %d\n",
  • ip_server, SERVER_PORT_CONNEXION );
  • return 0;
  • }
  • /******************************************************************************
  • * Fonction: CommunicatWithServer()
  • ** Premet d'echanger des donnees avec le Serveur. Recevoir ou Envoyer
  • ******************************************************************************/
  • int CommunicatWithServer ( SOCKET fdSock )
  • {
  • char data[500 + 1], *p = NULL;
  • int sock_err, c;
  • puts("\nVous pouvez saisir votre chaine :\n");
  • do
  • {
  • printf("> "); fflush(stdout);
  • fgets (data, sizeof(data), stdin);
  • p = strchr(data,'\n');
  • if (p == NULL)
  • while ((c = fgetc(stdin)) != '\n' && c != EOF);
  • else
  • *p = '\0';
  • /* Comande pour quitter */
  • if( strcmp(data, "/quit") == 0 )
  • break;
  • /* envoyer data */
  • if( (sock_err = SendData (fdSock, data)) == SOCKET_ERROR )
  • return 1;
  • }
  • while (1);
  • return 0;
  • }
  • /******************************************************************************
  • * Fonction: SendData()
  • ** Permet d'envoyer proprement un Bloc de données. Elle Retourne la taille
  • de donnee envoye'
  • ******************************************************************************/
  • int SendData ( SOCKET socket, char *data )
  • {
  • int const len_data = strlen (data);
  • int data_sent = 0, n;
  • char textmode_lendata[25];
  • sprintf (textmode_lendata, "%d\n", len_data);
  • /* Envoi de la taille de data, (en mode texte) */
  • n = send (socket, textmode_lendata, strlen(textmode_lendata), 0);
  • if ( n < 0)
  • {
  • perror("Error: sending data size");
  • return SOCKET_ERROR;
  • }
  • /* Envoyer le reste de donnees, s'il en reste */
  • while (data_sent < len_data)
  • {
  • n = send (socket, data + data_sent, len_data - data_sent, 0);
  • if (n >= 0)
  • data_sent += n;
  • else
  • return SOCKET_ERROR;
  • }
  • return (data_sent);
  • }
  • /********************************************************************
  • * 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 ...
  • *********************************************************************/
  • /* Verification que le compilateur est bien un compilateur C et pas C++ */
  • #ifdef __cplusplus
  • #error Be sure you are using a C compiler...
  • #endif
  • /**==================[ 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 );
  • /**************************************************************************
  • * 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);
  • }
/* Vous pouvez aussi télécharger le ZIP qui contiens les sources */

/********************************************************************
*   Client 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 ...
*********************************************************************/

/* Verifier que le compilateur est bien un compilateur C et pas C++ */
#ifdef __cplusplus
#error Be sure you are using a C compiler...
#endif

/**==================[ Si Windows ]================**/
#if defined (WIN32)
#include <winsock2.h>

/**================[ Si Gnu/Linux ]================**/
#elif defined (linux)

#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>

#define SERVER_PORT_CONNEXION 3113
char ip_server[15] = "127.0.0.1";  /* localhost */

int App (void);
int ConnectToServer (SOCKET*);
int CommunicatWithServer (SOCKET);
int SendData (SOCKET, char*);


/**************************************************************************
* Fonction main():
* La fonction principale ( le point d'entrer )...
***************************************************************************/
int main (void)
{
   int flag_main_exit = EXIT_SUCCESS;

/**==================[ Si Windows ]================**/
#if defined (WIN32)
   /* Initialiser WSAStartup() */
   WSADATA wsa_data;
   if ( WSAStartup (MAKEWORD (2, 2), &wsa_data) )
   {
      perror("Error: init WSAStartup()");
      return EXIT_FAILURE;
   }

   puts ("WIN: winsock2: OK");
#endif /**===========[ Fin teste Windows ]==========**/


   /* si app() retourne 1 c'est qu'elle a echoué */
   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 Client se connecte au serveur: ConnectToServer()
** Si connexion etablie, passer a' la communication CommunicatWithServer()
***************************************************************************/
int App (void)
{
   SOCKET fdsock;
   int sock_err;

   if ( ConnectToServer (&fdsock) )
      return 1; /* retourne 1 s'il y eu probleme */

   if ( CommunicatWithServer(fdsock) )
      return 1; /* retourne 1 s'il y eu probleme */

   /* Fin de communication, fermer socket proprement */
   shutdown (fdsock, 2);
   sock_err = closesocket (fdsock), fdsock = INVALID_SOCKET;
   if (sock_err == SOCKET_ERROR)
   {
      perror("Error: closesocket()");
      return 1;
   }

   return 0; /* Success */
}



/******************************************************************************
* Fonction: ConnectToServer()
** Connexion avec le serveur (ip_server) sur le port SERVER_PORT_CONNEXION
******************************************************************************/
int ConnectToServer ( SOCKET* fdSock )
{
	/* Declaration d'une structure sin de type SOCKADDR_IN
      Qui contiendra les infos consernant le serveur, (IP, port, type) */
   SOCKADDR_IN sin;

   /* Creation du socket: */
   if ( (*fdSock = 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", *fdSock);

   /* l'IP du serveur avec lequel on va ce connecter: */
   sin.sin_addr.s_addr = inet_addr(ip_server);
   /* le port avec lequel on va ce connecter sur le serveur: */
   sin.sin_port = htons (SERVER_PORT_CONNEXION);
   /* famille du protocol (IP): */
   sin.sin_family = AF_INET;


   if ( connect(*fdSock, (SOCKADDR *)&sin, sizeof sin) == SOCKET_ERROR )
   {
      perror("Error: connect");
      return 1;
   }

   printf ( "Vous etes maintenant connecter au serveur %s sur le port %d\n",
              ip_server, SERVER_PORT_CONNEXION );

   return 0;
}




/******************************************************************************
* Fonction: CommunicatWithServer()
** Premet d'echanger des donnees avec le Serveur.   Recevoir ou Envoyer
******************************************************************************/
int CommunicatWithServer ( SOCKET fdSock )
{
   char data[500 + 1], *p = NULL;
   int sock_err, c;

   puts("\nVous pouvez saisir votre chaine :\n");

   do
   {
      printf("> ");   fflush(stdout);
      fgets (data, sizeof(data), stdin);
      p = strchr(data,'\n');
      if (p == NULL)
         while ((c = fgetc(stdin)) != '\n' && c != EOF);
      else
         *p = '\0';

      /* Comande pour quitter */
      if( strcmp(data, "/quit") == 0 )
         break;

      /* envoyer data */
      if( (sock_err = SendData (fdSock, data)) == SOCKET_ERROR )
            return 1;
   }
   while (1);

   return 0;
}




/******************************************************************************
* Fonction: SendData()
** Permet d'envoyer proprement un Bloc de données. Elle Retourne la taille
   de donnee envoye'
******************************************************************************/
int SendData ( SOCKET socket, char *data )
{
   int const len_data = strlen (data);
   int data_sent = 0, n;
   char textmode_lendata[25];

   sprintf (textmode_lendata, "%d\n", len_data);

   /* Envoi de la taille de data, (en mode texte) */
   n = send (socket, textmode_lendata, strlen(textmode_lendata), 0);

   if ( n < 0)
   {
      perror("Error: sending data size");
      return SOCKET_ERROR;
   }

   /* Envoyer le reste de donnees, s'il en reste */
   while (data_sent < len_data)
   {
      n = send (socket, data + data_sent, len_data - data_sent, 0);

      if (n >= 0)
         data_sent += n;
      else
         return SOCKET_ERROR;
   }

   return (data_sent);
}




/********************************************************************
*   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 ...
*********************************************************************/
/* Verification que le compilateur est bien un compilateur C et pas C++ */
#ifdef __cplusplus
#error Be sure you are using a C compiler...
#endif

/**==================[ 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 );


/**************************************************************************
* 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);
}

Fichier Zip

Pour les "Membres Club", vous pouvez télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !
  •   Sockets C client-server
    •   Sockets C client-server
      • Client.cTélécharger ce fichier [Réservé aux membres club]Voir ce fichier6 717 octets
      • Client.exe_Télécharger ce fichier [Réservé aux membres club]20 927 octets
      • Server.exe_Télécharger ce fichier [Réservé aux membres club]22 289 octets
      • Serveur.cTélécharger ce fichier [Réservé aux membres club]Voir ce fichier8 269 octets

Télécharger le zip

Historique

11 septembre 2007 11:29:16 :
Ajout d'exécutables dans le ZIP.

Commentaires et avis

signaler à un administrateur
Commentaire de gree le 10/09/2007 21:10:26

bonjour,
tu pourrais mettre l'executable, SVP ?
merci pour ce code,
au revoir

signaler à un administrateur
Commentaire de Bug_Bug le 11/09/2007 11:34:23

Voilà, j'ai mis les exécutables Windows, Client et Server; il faut renommé le .exe_ en .exe

Toute fois, je ne vois pas l'intérêt de mettre les exécutables si tu peut compiler le code source !

signaler à un administrateur
Commentaire de gree le 11/09/2007 16:39:45

c parce que je ne comprends jamais comment compilé ce genre de code !
merci beaucoup,
au revoir

signaler à un administrateur
Commentaire de Bug_Bug le 12/09/2007 16:59:40

Comme tout les autre code source que tu compile en C !
Il faut juste faire le lien avec la lib ws2_32 ...

signaler à un administrateur
Commentaire de gree le 13/09/2007 18:20:36

j'ai toujours cru que c'était qu'en un fichier
au revoir

signaler à un administrateur
Commentaire de PhO3N1x_971 le 29/09/2007 03:35:43

commen faire un lien lib ws2_32 ?????? j'ai jamais su moi Non plus commnen compilé se genre de code un ami me l'avais di mais j'ai oublié :s

signaler à un administrateur
Commentaire de Bug_Bug le 01/10/2007 16:44:00

Quel ide utilises-tu ?
Code::Blocks ?  Dev-C++ ? Visual C++ ? ... ?

signaler à un administrateur
Commentaire de PhO3N1x_971 le 12/10/2007 02:33:33

Ba moi j'utilise Dev-C++ mais j'vais rentrer dans le visual C++ (2005 Express édition) DOnc si c'est possible je voudrais s'avoir pour les 2 :s stp

signaler à un administrateur
Commentaire de Division_par_zero le 17/10/2007 13:30:15 10/10

Excellent !

Je n'avais jamais eu à franchement me poser dans le domaine des sockets en C, et cette année pour mon projet, je me suis lancé dans la partie serveur, qui doit fonctionner sous windows et sous linux (Enfin je me suis imposé ces propres "limites").

Je n'ai pas encore tout testé car je compte bien le comprendre parfaitement, mais il est super ^^

Merci,
Cordialement.

signaler à un administrateur
Commentaire de OphidiaN le 09/11/2007 23:39:19 10/10

c'est super propre, super commenté... merci.

signaler à un administrateur
Commentaire de jboutkab le 31/12/2007 01:51:51

Salut
Merci pour ce code source, dans le client.c il faudrait ajouter string.h sinon ca risque de planter quand on compile
Merci

signaler à un administrateur
Commentaire de spleen46 le 12/05/2008 11:33:46

Bonjour, question surment trivial mais je debute dans lutiliation des socket lorsque jexecute le programme apres la connection quel commande doit ton mettre pour lenvoi de message merci beaucoup

signaler à un administrateur
Commentaire de bariland le 12/06/2009 12:41:39

code propre ,net ,bien commenté --------> la classe
a-tu penser au multithread oups je veux dire multiclient.
gérer la connection de plusieurs clients comme un chat par exemple et pourquoi pas penser a l'envoi de fichier text et binaire si tu arrive a envoyé des caractere c'est le meme principe ca sera vraiment interssant  

merci pour le code et c'est reutilisable  

signaler à un administrateur
Commentaire de djahiz le 14/06/2009 20:52:44

bonjour
j'ai lancé le serveur sur un autre pc mais je n'arrive pas a m'y connecter
j'ai mis l'adresse ip de cette autre pc a la place de celle du localhost dans la partie client mais ca ne marche pas
merci

Ajouter un commentaire

Discussions en rapport avec ce code source dans le forum

sockets!!!!!!!!!!!!!!! [ par dletozeun ] bonjour,J'ai encore un probleme avec les sockets:voila, g reussi a faire communiquer un serveur et un client su r 2 ordinateur distant mais cette conn Sockets asychrones et client serveur TCP [ par argali ] Bonjour,Est-ce qqun pourrait m'indiquer ou je pourrai trouver un cours complet sur les sockets asynchrones et leurs options (WSAAsyncSelect, FD_ACCEPT problemme avec les sockets [ par sirion ] Bonjour, j'ai un petit problemme avec les sockets. donc voila, j'ai essayer de faire un serveur/client qui recois 2msg chacun,&nbsp; mais ca merdouil Récupérer l'IP du client (SOCKETS) dans une app client/serveur [ par supergrey ] Bonjour, je voudrais savoir comment r&#233;cup&#233;rer l'IP du client a partir du programme serveur apr&#232;s le sock=accept(...);Merci d'avance ! Problème de sockets... [ par nightlord666 ] Bonjour ! J'essaie en ce moment de programmer un serveur multithread qui servira(peut-&#234;tre) &#224; un projet de MMORPG. Le serveur fonctionne nor Sockets sous MFC [ par DJONJ ] Bonjour, Peut être avez vous comme moi décortiqué un jour les codes sources exemples de Microsoft sous MFC CHATTER et CHATSRVR qui est un modèle cli client serveur [ par amenesca ] Bonjour,Généralement ,c'est le serveur qui écoute les sockets provenant des clients.Mais,si on veut que mème les autres clients connectés regardent le Client -> Serveur [ par norton ] Bonjour à tous. N'étant pas encore assez expérimenté dans le domaine des sockets je vous demande conseil.Je code sous Borland Builder C++ 6 avec les S Probleme Communication CLIENT SERVEUR FTP [ par kididouille ] Bonjour, je voudrais savoir comment dire à un client qu'un serveur accepte sa demande de connexion? Mon client: Filezilla Mon serveur: en cours de


Nos sponsors

Sondage...

CalendriCode

Juillet 2009
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
2728293031  

Consulter la suite du CalendriCode

Téléchargements

Logiciels à télécharger sur le même thème :

Comparez les prix Nouvelle version

Photothèque Nouveau !



Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés
Temps d'éxécution de la page : 0,218 sec

Google Coop CodeS-SourceS Google Coop CodeS-SourceS


Certaines images présentes sur le site (notament certains avatars) sont issues des collections IconShock, donc si vous souhaitez utiliser ces icons vous devez les acheter, ne les copiez pas et ne utilisez pas dans vos sites et applications sans les avoir commandé.