/* * ISA 563, Spring 2011 * Copyleft by Muhammad Abdulla */ #include #include #include #include #include #include #include #include /* * www-client.c -- demonstrates client-side socket operations */ #define HTTPPORT 80 int main ( int argc, char *argv[] ) { int sock; int retval; struct sockaddr_in sin ; struct hostent *hen ; FILE *fp; char line[1024]; char *host = "www.gmu.edu"; char *uri = "/"; if ( argc > 1 ) { host = argv[1]; } if ( argc > 2 ) { uri = argv[2]; } // create a TCP socket sock = socket ( AF_INET, SOCK_STREAM, 0 ) ; if ( sock < 0 ) { fprintf(stderr, "Could not create a socket.\n"); exit(1); } memset ( &sin, 0, sizeof(sin) ) ; sin.sin_family = AF_INET ; sin.sin_port = htons ( (short) HTTPPORT ) ; if ( hen = gethostbyname(host) ) { // first try alpha-numerical address memcpy ( &sin.sin_addr, hen->h_addr, hen->h_length ) ; } else { // doesn't seem to be alpha-numerical, try dotted decimal if ( inet_pton ( AF_INET, host, &sin.sin_addr ) < 1 ) { fprintf(stderr, "Invalid hostname: %s.\n", host); exit(1); } } retval = connect ( sock, (struct sockaddr *) &sin, sizeof(sin) ) ; if ( retval < 0 ) { fprintf(stderr, "Could not connect to host %s.\n", host); return -1; } fp = fdopen(sock, "r+"); if ( fp == NULL ) { fprintf(stderr, "fdopen error.\n"); return -1; } fprintf(fp, "GET %s\n", uri); while ( fgets(line, sizeof(line), fp) != NULL ) { fprintf(stdout, "%s", line); } }