Tobiahao

S01_BSD_02_CLIENT

Jan 23rd, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.07 KB | None | 0 0
  1. /*
  2. Napisz programy, które prześlą plik o rozmiarze większym od 1 MiB między
  3. dwoma komputerami, z użyciem protokołu TCP/IP. Sprawdź , co się stanie, jeśli
  4. plik będzie wysyłany w jednym komunikacie.
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <sys/socket.h>
  10. #include <sys/types.h>
  11. #include <sys/stat.h>
  12. #include <sys/sendfile.h>
  13. #include <arpa/inet.h>
  14. #include <unistd.h>
  15. #include <fcntl.h>
  16. #include <string.h>
  17.  
  18. #define SERVER_IP "127.0.0.1"
  19. #define SERVER_PORT 1919
  20.  
  21. void error_handler(const char *msg)
  22. {
  23.     perror(msg);
  24.     exit(EXIT_FAILURE);
  25. }
  26.  
  27. int main(int argc, char *argv[])
  28. {
  29.     if(argc != 2) {
  30.         fprintf(stderr, "Niepoprawna liczba argumentow\nUzycie: %s [plik, ktory ma zostac przeslany na serwer]\n", argv[0]);
  31.         return EXIT_FAILURE;
  32.     }
  33.  
  34.     int client_socket;
  35.     int fd;
  36.     struct sockaddr_in server_addr;
  37.     struct stat file_stat;
  38.     char file_size[BUFSIZ];
  39.     int remain_data, sent_bytes;
  40.     off_t offset;
  41.  
  42.     if((fd = open(argv[1], O_RDONLY)) == -1)
  43.         error_handler("open");
  44.     if(fstat(fd, &file_stat) == -1)
  45.         error_handler("fstat");
  46.  
  47.     sprintf(file_size, "%ld", file_stat.st_size);
  48.  
  49.     if(!inet_aton(SERVER_IP, &server_addr.sin_addr))
  50.         error_handler("inet_aton");
  51.     server_addr.sin_family = AF_INET;
  52.     server_addr.sin_port = htons(SERVER_PORT);
  53.     memset(server_addr.sin_zero, '\0', 8); 
  54.  
  55.     if((client_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1)
  56.         error_handler("socket");
  57.     if(connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
  58.         error_handler("connect");
  59.  
  60.     printf("Polaczono z serwerem!\n");
  61.  
  62.     if(send(client_socket, file_size, sizeof(file_size), 0) == -1)
  63.         error_handler("write");
  64.     printf("Wysylam plik o rozmiarze %ld bajtow...\n", file_stat.st_size);
  65.  
  66.     offset = 0;
  67.     remain_data = file_stat.st_size;
  68.     while(((sent_bytes = sendfile(client_socket, fd, &offset, BUFSIZ)) > 0) && (remain_data > 0))
  69.         remain_data -= sent_bytes;
  70.  
  71.     if(sent_bytes == -1)
  72.         error_handler("sendfile");
  73.  
  74.     printf("Pomyslnie wyslano plik!\n");
  75.  
  76.     if(close(client_socket) == -1)
  77.         error_handler("close");
  78.  
  79.     return EXIT_SUCCESS;
  80. }
Add Comment
Please, Sign In to add comment