Tobiahao

S01_BSD_04_CLIENT

Jan 23rd, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.04 KB | None | 0 0
  1. /*
  2. Napisz programy przesyłające plik o wielkości przekraczającej 1 MiB między
  3. dwoma komputerami, przy użyciu protokołu bezpołączeniowego.
  4. */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <sys/types.h>
  9. #include <sys/socket.h>
  10. #include <sys/stat.h>
  11. #include <arpa/inet.h>
  12. #include <netinet/in.h>
  13. #include <fcntl.h>
  14. #include <unistd.h>
  15. #include <string.h>
  16.  
  17. #define SERVER_PORT 1919
  18. #define SERVER_IP "127.0.0.1"
  19. #define END_FLAG "--END_OF_TRANSFER--"
  20.  
  21. void error_handler(const char *msg)
  22. {
  23.     perror(msg);
  24.     exit(EXIT_SUCCESS);
  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 wyslany]\n", argv[0]);
  31.         return EXIT_FAILURE;
  32.     }
  33.  
  34.     int sockfd, filefd;
  35.     struct sockaddr_in sockaddr;
  36.     struct stat file_stat;
  37.     int remain_bytes;
  38.     ssize_t sent_bytes;
  39.     char buffer[BUFSIZ];
  40.  
  41.     if(!inet_aton(SERVER_IP, &sockaddr.sin_addr))
  42.         error_handler("inet_aton");
  43.     sockaddr.sin_family = AF_INET;
  44.     sockaddr.sin_port = htons(SERVER_PORT);
  45.     memset(sockaddr.sin_zero, '\0', 8);
  46.  
  47.     if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
  48.         error_handler("socket");
  49.  
  50.     if((filefd = open(argv[1], O_RDONLY)) == -1)
  51.         error_handler("open");
  52.     if(fstat(filefd, &file_stat) == -1)
  53.         error_handler("stat");
  54.     remain_bytes = file_stat.st_size;
  55.  
  56.     sprintf(buffer, "%d", remain_bytes);
  57.     if(sendto(sockfd, buffer, BUFSIZ, 0, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) == -1)
  58.         error_handler("sendto");
  59.     printf("Wysylam plik o rozmiarze %d bajtow...\n", remain_bytes);
  60.  
  61.     memset(buffer, '\0', BUFSIZ);
  62.    
  63.     while((sent_bytes = read(filefd, buffer, BUFSIZ)) > 0)
  64.         if(sendto(sockfd, buffer, sent_bytes, 0, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) == -1)
  65.             error_handler("sendto");
  66.  
  67.     if(sendto(sockfd, END_FLAG, strlen(END_FLAG), 0, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) == -1)
  68.         error_handler("sendto");
  69.  
  70.     printf("Plik zostal wyslany!\n");
  71.  
  72.     if((close(sockfd) == -1) || (close(filefd) == -1))
  73.         error_handler("close");
  74.  
  75.     return EXIT_SUCCESS;
  76. }
Add Comment
Please, Sign In to add comment