Advertisement
Guest User

server.c

a guest
Aug 13th, 2013
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.56 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <netdb.h>
  4. #include <netinet/in.h>  
  5.  
  6. #define BUFFER_SIZE 1024
  7. #define NAME_SIZE 2048
  8.  
  9. int handling(int c)  {
  10.     char buffer[BUFFER_SIZE], name[NAME_SIZE];
  11.     int bytes;
  12.  
  13.     strcpy(buffer, "My name is: ");
  14.    
  15.     bytes = send(c, buffer, strlen(buffer), 0);
  16.    
  17.     if (bytes == -1) return -1;
  18.    
  19.     bytes = recv(c, name, sizeof(name), 0);
  20.    
  21.     if (bytes == -1) return -1;
  22.  
  23.     name[bytes - 1] = '\0';
  24.  
  25.     sprintf(buffer, "Hello %s, nice to meet you!\r\n", name);
  26.    
  27.     bytes = send(c, buffer, strlen(buffer), 0);
  28.    
  29.     if (bytes == -1) return -1; return 0;  
  30. }
  31.    
  32. int main(int argc, char *argv[])  {
  33.     int s, c, cli_size;
  34.     struct sockaddr_in srv, cli;
  35.    
  36.     if (argc != 2) {
  37.         fprintf(stderr, "usage: %s port\n", argv[0]);
  38.         return 1;
  39.     }
  40.    
  41.     s = socket(AF_INET, SOCK_STREAM, 0);
  42.    
  43.     if (s == -1) {
  44.         perror("socket() failed");
  45.         return 2;
  46.     }
  47.    
  48.     srv.sin_addr.s_addr = INADDR_ANY;
  49.     srv.sin_port = htons( (unsigned short int) atol(argv[1]));
  50.     srv.sin_family = AF_INET;
  51.    
  52.     if (bind(s, &srv, sizeof(srv)) == -1) {
  53.         perror("bind() failed");
  54.         return 3;
  55.     }
  56.    
  57.     if (listen(s, 30) == -1) {
  58.         perror("listen() failed");
  59.         return 4;
  60.     }
  61.    
  62.     for(;;) {
  63.        
  64.         //c = accept(s, (struct sockaddr *) &cli, sizeof(cli));
  65.         c = accept(s, NULL, NULL);
  66.  
  67.         if (c == -1) {
  68.             perror("accept() failed");
  69.             return 5;
  70.         }
  71.        
  72.         printf("client from %s", inet_ntoa(cli.sin_addr));
  73.        
  74.         if (handling(c) == -1) fprintf(stderr, "%s: handling() failed", argv[0]);
  75.        
  76.         close(c);
  77.     }
  78.    
  79.     return 0;  
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement