Logo  

CS473 - Computer Networks

Displaying exercises/e5/solution/get.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>

#define K	1024

#define PORT	47350 // Your servers port number

/*
 * get.c:
 *   A program to connect to a server and receive data into a file.
 */
int main(int argc, char *argv[])
{
  struct hostent *he;
  struct sockaddr_in server;
  char buf[K];
  int sock, fd, r, n;

  if (argc < 3) {
    fprintf(stderr,"Usage: get <hostname> <filename>\n");
    return 0;
  }

  // Use open to open the file specified by argv[2] for writing, create the
  // file if it doesn't exist and truncate the file if it does.
  // Print an error message and exit if the open fails.
  fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0666);
  if (fd < 0) {
    perror("open");
    exit(1);
  }

  // Create a SOCK_STREAM internet socket:
  sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock < 0) {
    perror("socket");
    exit(1);
  }

  // Setup the severs address, use gethostbyname() to get the address:
  server.sin_family = AF_INET;
  if ((he = gethostbyname(argv[1])) == NULL) {
    fprintf(stderr,"Unknown host: %s\n", argv[1]);
    exit(1);
  }
  memcpy(&server.sin_addr, he->h_addr, he->h_length);
  server.sin_port = htons(PORT);

  // Use connect() to connect to the server:
  if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
    perror("connect");
    exit(1);
  }

  // In a loop, read K sized buffers from the socket and write the data into
  // the file until the socket connection is closed.  Make sure to only write
  // as much data into the file as was actually read from the socket.
  while((r = read(sock, buf, K)) > 0) {
    if (write(fd, buf, r) < 0) break;
  }
  return 0;
}