// Run like this: simple_client address port // Results in argv ["./simple_client", "address", "port"] #include #include #include #include #include #include #include #include #include #include int main(int argc, char ** argv){ if(argc < 4){ printf("Usage: %s hostname port filename\n", argv[0]); return 1; } struct sockaddr_in sad; sad.sin_port = htons(atoi(argv[2])); sad.sin_family = AF_INET; int skt = socket(AF_INET, SOCK_STREAM, 0); // do a dns lookup struct hostent* entry = gethostbyname(argv[1]); if(!entry){ if(h_errno == HOST_NOT_FOUND){ printf("This is our own message that says the host wasn't found\n"); } herror("gethostbyname"); return 1; } struct in_addr **addr_list = (struct in_addr**)entry->h_addr_list; struct in_addr* c_addr = addr_list[0]; char* ip_string = inet_ntoa(*c_addr); sad.sin_addr = *c_addr; // copy the address we found into sad // Finally done with DNS! printf("Connecting to: %s\n", ip_string); if( connect(skt, (struct sockaddr*)&sad, sizeof(struct sockaddr_in)) ){ perror("connect"); return 1; } uint16_t filename_length = strlen(argv[3]); write(skt, &filename_length, 2); write(skt, argv[3], filename_length); int64_t file_size; read(skt, &file_size, 8); // We'll assume this worked if(file_size <= 0) { printf("No file found: %s\n"); return 1; } else { printf("File %s found, size is %ld\n", file_size); } char *file_space = (char*)malloc(file_size); recv(skt, file_space, file_size, MSG_WAITALL); int output_fd = open(argv[3], O_WRONLY | O_CREAT | O_TRUNC, 0644); write(output_fd, file_space, file_size); close(skt); return 0; }