Advertisement
Benlahbib_Abdessamad

server.c

May 21st, 2015
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.17 KB | None | 0 0
  1. #include <sys/socket.h>
  2. #include <netinet/in.h>
  3. #include <arpa/inet.h>
  4. #include <stdlib.h>
  5. #include <errno.h>
  6. #include <stdio.h>
  7. #include <unistd.h>
  8. #include <string.h>
  9.  
  10.  
  11.  
  12. int main()
  13. {
  14.   int sockfd,rec_sock,sockfd1, len,i;
  15.   struct sockaddr_in addr, recaddr;
  16.    char buf[100],buf1[100];
  17.    int port;
  18.    FILE* fichier = NULL;
  19.  
  20.  
  21.  
  22.   if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  23.     perror(": Can't get socket");
  24.     exit(1);
  25.   }
  26.  
  27.   addr.sin_addr.s_addr = INADDR_ANY;
  28.   addr.sin_family = AF_INET;
  29.   addr.sin_port = htons(4450);
  30.  
  31.   if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
  32.     perror(": bind");
  33.     exit(1);
  34.   }
  35.  
  36.   printf("ip = %s, port = %d\n", inet_ntoa(addr.sin_addr), addr.sin_port);
  37.  
  38.   if (listen(sockfd, 5) < 0) {
  39.     perror(": bind");
  40.     exit(1);
  41.   }
  42.  
  43.  
  44.    while (1)
  45. {
  46.        rec_sock = accept(sockfd, (struct sockaddr *)(&recaddr), &len);
  47.        
  48.   if (rec_sock < 0) {
  49.     perror(": accept");
  50.     exit(1);
  51.   }
  52.  
  53.   /* print the remote socket information */
  54.  
  55.   printf("remote machine = %s, port = %x, %x.\n", inet_ntoa(recaddr.sin_addr), recaddr.sin_port, ntohs(recaddr.sin_port));
  56.  
  57.  
  58.  
  59.   write(rec_sock, "connecter", 20);
  60.  
  61.   for (i=0; i<100; i++)
  62.   buf[i] = '\0';
  63.   read(rec_sock, buf, 99);
  64.   printf("port aleatoire : %s\n", buf);
  65.  
  66.   // put client info in a txt file
  67.  
  68.   fichier = fopen("tmp.txt", "w");
  69.   if (fichier != NULL)
  70.     {
  71.     fprintf(fichier,"Remote machine ip = %s  Port = %s \n",inet_ntoa(recaddr.sin_addr),buf);
  72.     fclose(fichier);
  73.     }
  74.     printf("\n \n")
  75.    
  76.     port=atoi(buf);
  77.  
  78.   recaddr.sin_family = AF_INET;
  79.   recaddr.sin_port = htons(port);
  80.  
  81.   if ((sockfd1 = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  82.     perror(": Can't get socket");
  83.     exit(1);
  84.   }
  85.  
  86.   if (connect(sockfd1, (struct sockaddr *)&recaddr, sizeof(recaddr)) < 0) {
  87.     printconnerror();
  88.     perror(": connect");
  89.     exit(1);
  90.   }
  91.  
  92.   for (i=0; i<100; i++)
  93.   buf[i] = '\0';
  94.   read(sockfd, buf, 99);
  95.   printf("Chaine = %s\n", buf);
  96.   printf("Commande a executer chez le client \n");
  97.   scanf("%s",&buf1);
  98.   write(sockfd1,buf1,20);
  99.  
  100.  
  101. }
  102.  
  103.   sleep(20);
  104.   exit(1);
  105.  
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement