#include #include #include #include #include #include #include #include struct in_addr* name_to_IP_addr(char* hostname) { struct hostent* hostp; /* Gets host info for the given hostname */ hostp = gethostbyname(hostname); /* Extract first IP address (in network byte order ) & return it */ return (struct in_addr*)hostp->h_addr_list[0]; } int connect_to(struct in_addr* ipAddress, int port) { struct sockaddr_in socketAddr; int fd; /* Create socket - SOCK_STREAM means TCP */ fd = socket(AF_INET, SOCK_STREAM, 0); if(fd < 0) { perror("Error creating socket"); exit(1); } /* Create a structure that contains info on the address we want to ** connect to. */ socketAddr.sin_family = AF_INET; /* Family = Internet */ socketAddr.sin_port = htons(port); /* Port number in network byte order */ socketAddr.sin_addr.s_addr = ipAddress->s_addr; /* IP address we're ** connecting to. */ /* Try to connect to the given address/port */ if(connect(fd, (struct sockaddr*)&socketAddr, sizeof(socketAddr)) < 0) { perror("Error connecting"); exit(1); } return fd; /* Now have a connected file descriptor */ } void send_HTTP_request(int fd, char* file) { char* requestString; /* Construct the HTTP request string */ requestString = (char*)malloc(strlen(file) + 20); sprintf(requestString, "GET %s HTTP/1.0\r\n\r\n", file); /* Send the string to the file descriptor */ /* Should really loop until all bytes sent OR error happens. ** Note that write() returns number of bytes written */ if(write(fd, requestString, strlen(requestString)) < 1) { perror("Write error"); exit(1); } } void get_and_output_HTTP_response(int fd) { char buffer[1024]; int numBytesRead; int eof = 0; while(!eof) { /* Read up to 1024 bytes from connection */ numBytesRead = read(fd, buffer, 1024); if(numBytesRead < 0) { perror("Read error\n"); exit(1); } else if(numBytesRead == 0) { /* End of file - no more data to be received */ eof = 1; } else { /* Got some data - write it out to standard output */ fwrite(buffer, 1, numBytesRead, stdout); } } } int main(int argc, char* argv[]) { int fd; struct in_addr* ipAddress; if(argc != 2) { fprintf(stderr, "Usage: %s hostname\n", argv[0]); exit(1); } ipAddress = name_to_IP_addr(argv[1]); if(!ipAddress) { fprintf(stderr, "%s is not a valid hostname\n", argv[1]); exit(1); } fd = connect_to(ipAddress, 80); send_HTTP_request(fd, "/"); get_and_output_HTTP_response(fd); close(fd); return 0; }