Previous: Implementing a ‘display_result’ Function, Up: Steps in Implementing an Insecure HTTP Client [Index]
The main routine that coordinates all of this is shown in Listing 1-3.
/** * Simple command-line HTTP client. */ int main( int argc, char *argv[ ] ) { int client_connection; char *host, *path; struct hostent *host_name; struct sockaddr_in host_address; if ( argc < 2 ) { fprintf( stderr, "Usage: %s: <URL>\n", argv[ 0 ] ); return 1; } if ( parse_url( argv[ 1 ], &host, &path ) == -1 ) { fprintf( stderr, "Error - malformed URL '%s . \n", argv[ 1 ] ); return 1; } printf( "Conecting to host '%s'\n", host );
After the URL has been parsed and the host is known, you must establish a
socket to it. In order to do this, convert it from a human-readable host name,
as ‘www.server.com’, to a dotted-decimal IP address, such as ‘100.218.64.2’.
You call the standard gethostbyname
library function to do this, and connect
to the server. This is shown in Listing 1-4.
// Step 1: open a socket connection on http port with the destination host client_connection = socket( PF_INET, SOCK_STREAM, 0 ); if ( !client_connection ) { perror( "Unable to create a local socket" ); return 2; } host_name = gethostbyname( host ); if ( !host_name ) { perror( "Error in name resolution" ); return 3; } host_address.sin_family = AF_INET; host_address.sin_port = htons( HTTP_PORT ); memcpy( &host_address.sin_addr, host_name->h_addr_list[ 0 ], sizeof( struct in_addr ) ); if ( connect( client_connection, ( struct sockaddr * ) &host_address, sizeof( host_address ) ) == -1 ) { perror( "Unable to connect to host" ); return 4; } printf( "Retrieving document: '%s'\n", path );
Assuming nothing went wrong:
You now have a usable (cleartext) socket with which to exchange data with the web server. Issue a ‘GET’ command, display the result, and close the socket, as shown in Listing 1-5.
// Step 2: Issue a GET command http_get( client_connection, path, host ); display_result( client_connection ); printf( "Shutting down.\n" ); if (close( client_connection ) == -1 ) { perror( "Error closing client connection" ); return 5; } return 0; }