
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <error.h>

int main(int argc, char *argv[])
{
    int s, rc;
    struct hostent *h;
    struct sockaddr_in sa;
    char buf[1025];
    
    /* STEP C.1 - Open a TCP/IPv4 stream socket. */
    s = socket(PF_INET, SOCK_STREAM, 0);
    if (s < 0) {
        perror("Could not open socket");
        return 1;
    }

    /* Resolve the Name (argv[1]) to an address. */
    h = gethostbyname(argv[1]);
    /* TODO: Care about missing argv[1]. */
    sa.sin_family = AF_INET;
    sa.sin_addr = *(struct in_addr *)h->h_addr_list[0];
    sa.sin_port = htons(8080); 
    /* TODO: Care about failures and unexpected address types. */

    /* STEP C.2 - Connect to the server. */
    rc = connect(s, (struct sockaddr *)&sa, sizeof(sa));
    if (rc < 0) {
        perror("Could not connect to server");
        return 1;
    }

    /* STEP C.3 - Write request to the outgoing stream. */
    sprintf(buf, "GET %s HTTP/1.0\n\n", argv[2]);
    write(s, buf, strlen(buf));
    /* TODO: Care about missing argv[2]. */
    
    /* STEP C.4 - Read and process the response from the incoming stream. */
    while ((rc = read(s, buf, 1024)) > 0) {
        buf[rc] = '\0';
        printf("%s", buf);
        /* TODO: We should not assume that all data is printable. */
    }

    /* STEP C.5 - Close the socket. */
    close(s);
    
    return 0;
}

