Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdlib>
- #include <fstream>
- #include <iostream>
- #include <netdb.h>
- #include <stdint.h>
- #include <string>
- #include <sys/socket.h>
- #include <unistd.h>
- void error(const char *message) {
- std::cout << message << "\n";
- exit(EXIT_FAILURE);
- }
- void check_write(int sockfd, const void *data, size_t size) {
- if (write(sockfd, data, size) != size) {
- error("Failed to write to socket");
- }
- }
- int check_connect(const addrinfo *ai) {
- int sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (sockfd == -1)
- error("Failed to open socket");
- if (connect(sockfd, ai->ai_addr, ai->ai_addrlen) != 0)
- error("Failed to connect socket");
- return sockfd;
- }
- void send_file(int sockfd, const char *filename) {
- std::ifstream file(filename, std::ifstream::binary);
- if (file) {
- file.seekg(0, file.end);
- size_t file_size = file.tellg();
- file.seekg(0, file.beg);
- uint32_t net_len = htonl(strlen(filename));
- check_write(sockfd, &net_len, sizeof(net_len));
- check_write(sockfd, filename, strlen(filename));
- uint32_t net_file_size = htonl(file_size);
- check_write(sockfd, &net_file_size, sizeof(net_file_size));
- char buffer[4096];
- do {
- file.read(buffer, 4096);
- check_write(sockfd, buffer, file.gcount());
- } while (file);
- } else {
- error("Failed to open file");
- }
- }
- void connect_and_send_file(const addrinfo *ai, const char *filename) {
- int sockfd = check_connect(ai);
- send_file(sockfd, filename);
- close(sockfd);
- }
- void resolve_host_and_send_file(const char *host, const char *port,
- const char *filename) {
- addrinfo *ai = NULL;
- if (getaddrinfo(host, port, NULL, &ai) == 0) {
- connect_and_send_file(ai, filename);
- freeaddrinfo(ai);
- } else {
- error("Failed to resolve service");
- }
- }
- int main(int argc, char *argv[]) {
- if (argc == 4) {
- resolve_host_and_send_file(argv[1], argv[2], argv[3]);
- } else {
- error("Usage: client <host> <port> <file_name>");
- }
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement