//================================================================ // browser.cc // ¸¶»Ï web browser // Copyright (C) Naoki Watanabe. 1999. All rights reserved. //================================================================ #include #include #include #include #include #include #include int main( int argc, char* argv[] ) { u_short port = 80; char hostname[256], pathname[256]; // parse the URL. if( 2 != argc || ( 3 != sscanf( argv[1], "http://%[^:]:%hu%s", hostname, &port, pathname ) && 2 != sscanf( argv[1], "http://%[^/]%s", hostname, pathname ) ) ){ fprintf( stderr, "Usage: browser http://hostname:port/pathname\n" ); exit(1); } // get the IP address of the web server. struct hostent* hp; if( (hp = gethostbyname( hostname )) == NULL ){ fprintf( stderr, "gethostbyname\n"); exit(1); } // get the address of the internet domain socket to the HTTPD. struct sockaddr_in sadd; sadd.sin_family = AF_INET; sadd.sin_port = htons(port); sadd.sin_addr = *(struct in_addr*) hp->h_addr; // create a new socket. int s = socket( AF_INET, SOCK_STREAM, 0 ); // connect the socket to the httpd. if( connect( s, (sockaddr*)&sadd, sizeof(sockaddr_in) ) < 0 ){ perror("connect"); exit(1); } size_t len; char buf[4096]; // send a request to the httpd. len = sprintf( buf, "GET %s\r\n", pathname ); send( s, buf, len, 0 ); // reveive contents and output them. while( (len=recv( s, buf, sizeof(buf), 0 ))>0 ) write( 1, buf, len ); shutdown( s, 2 ); return 0; }