Advertisement
ikseek

filesender_client

Oct 27th, 2016
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <fstream>
  3. #include <iostream>
  4. #include <netdb.h>
  5. #include <stdint.h>
  6. #include <string>
  7. #include <sys/socket.h>
  8. #include <unistd.h>
  9.  
  10. void error(const char *message) {
  11.   std::cout << message << "\n";
  12.   exit(EXIT_FAILURE);
  13. }
  14.  
  15. void check_write(int sockfd, const void *data, size_t size) {
  16.   if (write(sockfd, data, size) != size) {
  17.     error("Failed to write to socket");
  18.   }
  19. }
  20.  
  21. int check_connect(const addrinfo *ai) {
  22.   int sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  23.   if (sockfd == -1)
  24.     error("Failed to open socket");
  25.   if (connect(sockfd, ai->ai_addr, ai->ai_addrlen) != 0)
  26.     error("Failed to connect socket");
  27.   return sockfd;
  28. }
  29.  
  30. void send_file(int sockfd, const char *filename) {
  31.   std::ifstream file(filename, std::ifstream::binary);
  32.   if (file) {
  33.     file.seekg(0, file.end);
  34.     size_t file_size = file.tellg();
  35.     file.seekg(0, file.beg);
  36.  
  37.     uint32_t net_len = htonl(strlen(filename));
  38.     check_write(sockfd, &net_len, sizeof(net_len));
  39.     check_write(sockfd, filename, strlen(filename));
  40.     uint32_t net_file_size = htonl(file_size);
  41.     check_write(sockfd, &net_file_size, sizeof(net_file_size));
  42.     char buffer[4096];
  43.     do {
  44.       file.read(buffer, 4096);
  45.       check_write(sockfd, buffer, file.gcount());
  46.     } while (file);
  47.   } else {
  48.     error("Failed to open file");
  49.   }
  50. }
  51.  
  52. void connect_and_send_file(const addrinfo *ai, const char *filename) {
  53.   int sockfd = check_connect(ai);
  54.   send_file(sockfd, filename);
  55.   close(sockfd);
  56. }
  57.  
  58. void resolve_host_and_send_file(const char *host, const char *port,
  59.                                 const char *filename) {
  60.   addrinfo *ai = NULL;
  61.   if (getaddrinfo(host, port, NULL, &ai) == 0) {
  62.     connect_and_send_file(ai, filename);
  63.     freeaddrinfo(ai);
  64.   } else {
  65.     error("Failed to resolve service");
  66.   }
  67. }
  68.  
  69. int main(int argc, char *argv[]) {
  70.   if (argc == 4) {
  71.     resolve_host_and_send_file(argv[1], argv[2], argv[3]);
  72.   } else {
  73.     error("Usage: client <host> <port> <file_name>");
  74.   }
  75.   return EXIT_SUCCESS;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement