#include #include #include #include #include #include #include #define MAXLINE 10240 #define defaultURL "/" struct sockaddr_in server_addr; /* server's address */ char *programName; void usage() { fprintf(stderr, "usage: %s host URL\n", programName); exit(-1); } main(argc, argv) int argc; char **argv; { struct hostent *hostentry; char *url; char recvline[MAXLINE + 1]; char GetCMD[MAXLINE + 1]; int n; int client_socket_fd; /* Socket to client, server */ int sz; int optval; /* the socket option value */ int optlen; /* length of the option value */ long inaddr; programName = argv[0]; if ((argc < 2) || (argc > 3)) /* Check the arguments first. */ usage(); /* initialize the server address structure */ memset( (char*)&server_addr, 0, sizeof(server_addr)); server_addr.sin_family=PF_INET; server_addr.sin_port=htons(80); /* 80 is the TCP port number for HTTP */ /* Assume if the first character is a digit that it is an decimal dot notation IP address */ if (isdigit(argv[1][0]) > 0) { server_addr.sin_addr.s_addr = inet_addr(argv[1]); } else { hostentry=gethostbyname(argv[1]); if ( hostentry == NULL) { fprintf(stderr, "invalid host name for server: %s", argv[1]); exit(1); } /* Note that below we use only the first address, if the host has several possible address; the better thing to do would be to try each of the addresses in the list */ server_addr.sin_addr.s_addr = inet_addr(inet_ntoa(hostentry->h_addr_list[0])); }; if (server_addr.sin_addr.s_addr == -1) { fprintf(stderr, "could not get an address for: %s", argv[1]); exit(1); } client_socket_fd = socket(PF_INET, SOCK_STREAM, 0); /* create a socket */ if (client_socket_fd < 0) { perror("Unable to open socket"); exit(1); }; /* the code below allows you to very the sizeof your received buffer */ optval = 512; /* to be set as size of receive buffer */ /* note that it must be passed via a char* */ optlen = 4; /* size of the option in bytes */ if (setsockopt(client_socket_fd, SOL_SOCKET, SO_RCVBUF, (char*)&optval, optlen) == -1) { fprintf( stderr, "%s error in setting receive buffer size:", argv[0]); perror( "setsockopt"); close(client_socket_fd); exit(1); } if (connect(client_socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { perror("Unable to connect with socket"); close(client_socket_fd); exit(1); }; if (argc > 2) sprintf(GetCMD, "GET %s HTTP/1.0\r\n\r\n", argv[2]); else { sprintf(GetCMD, "GET %s HTTP/1.0\r\n\r\n", defaultURL); }; /* fprintf(stderr, "GetCMD: %s\n", GetCMD); */ if (write(client_socket_fd, GetCMD, strlen(GetCMD)) < 0) { perror("socket write error"); }; while ( (n = read(client_socket_fd, recvline, MAXLINE)) > 0) { recvline[n] = 0; /* null terminate */ if (fputs(recvline, stdout) == EOF) perror("fputs error"); } if (n < 0) perror("read error"); close(client_socket_fd); /* close the socket */ exit(0); }